AVAudioPlayer

AVAudioPlayer

The AVAudioPlayer class lets you play sound in any audio format available in iOS and macOS.
AVAudioPlayer可以播放任何iOS和macOS支持的音频格式(.mp3、.caf、.aac)的本地音频文件

do{
        let audioPlayer = try AVAudioPlayer.init(contentsOf: audioUrl)
        audioPlayer.rate = 1.5  //播放速率
        audioPlayer.numberOfLoops = 0//循环播放次数
        audioPlayer.volume = 0.8//音量
        audioPlayer.pan = 0.0 //切换声道 -1.0左声道 0 双声道 1.0 右声道
        audioPlayer.delegate = self//
        audioPlayer.play()
}catch{
}

AVAudioPlayerDelegate

 //播放结束
   func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    }
    
//解码失败
  func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
        print("解码失败")
    }
    
//中断开始
    func audioPlayerBeginInterruption(_ player: AVAudioPlayer) {
    }
    
//中断结束
    func audioPlayerEndInterruption(_ player: AVAudioPlayer, withOptions flags: Int) {
    }

通知处理中断

NotificationCenter.default.addObserver(self, selector: #selector(handleAudioInterrupution), name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance())
      
@objc func handleAudioInterrupution(notification:NSNotification ){
    let userInfo = notification.userInfo
    guard userInfo != nil else {
        return
    }
    
    if let ininterruptionType = userInfo![AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType{
        if ininterruptionType == AVAudioSessionInterruptionType.began{
            print("AVAudioSessionInterruptionType.began")
        }else{
            if let options = userInfo![AVAudioSessionInterruptionOptionKey] as? AVAudioSessionInterruptionOptions, options == AVAudioSessionInterruptionOptions.shouldResume{
                print("AVAudioSessionInterruptionType.end let's resume")
            }
        }
    }
    
}

通知处理音道变化

NotificationCenter.default.addObserver(self, selector: #selector(handleAudioSessionRouteChange), name: NSNotification.Name.AVAudioSessionRouteChange, object: AVAudioSession.sharedInstance())

@objc func handleAudioSessionRouteChange(notification:NSNotification){
    let userInfo = notification.userInfo
    guard userInfo != nil else {
        return
    }
    if let reason = userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt{
        if reason == AVAudioSessionRouteChangeReason.oldDeviceUnavailable.rawValue{//旧设备输出端口移除
            if let routeDescription = userInfo?[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription{
                let portDescription = routeDescription.outputs[0]
                if portDescription.portName == "耳机"{
                    self.audioPlayer?.pause()
                }
            }
        }else if reason == AVAudioSessionRouteChangeReason.newDeviceAvailable.rawValue{//新设备输出端口接入
            let routeDescription = AVAudioSession.sharedInstance().currentRoute
            let portDescription = routeDescription.outputs[0]
            if portDescription.portName == "耳机",audioPlayer != nil,selIndex>=0{
                self.audioPlayer?.play()
            }
        }
    }
}

切换声道

func resetAuidoSession(isRecord:Bool) {
    let audioSession = AVAudioSession.sharedInstance()
    do{
        try audioSession.setCategory(isRecord ? AVAudioSessionCategoryPlayAndRecord : AVAudioSessionCategoryPlayback)
        try audioSession.setActive(true)
    }catch{
        
    }
}

参考链接:AVAudioPlayer

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 所有的iOS App都具有默认的音频会话,它定义了以下行为:可以播放音频,但是不能录制音频。静音模式下App播放的...
    彬至睢阳阅读 4,377评论 5 5
  • Linear PCM 在介绍Core Audio之前,先介绍一下最常用的非压缩数字音频格式Linear PCM(线...
    huangjun0阅读 4,422评论 0 2
  • 简述 AVAudioPlayer 是一个属于 AVFoundation.framework 的一个类,它的功能类似...
    TianBai阅读 24,414评论 13 168
  • AVAudioPlayer 在iOS程序中,音频播放随处可见,有的声音只有1秒,有的声音好几分钟 。iOS支持的音...
    Joker_King阅读 25,643评论 7 17
  • 这样的夜里我睡不着 夜晚的栏杆的影子被车子拉着跑 跑了一半又扔下它 我就像这影子 我的内心拉着我往前跑,像那辆车 ...
    宝宝丢雪阅读 310评论 1 1