代码改变世界

AVAudioSession.sharedInstance()导致其他App背景音乐被停止

2018-10-11 11:13  法子  阅读(1861)  评论(0编辑  收藏  举报

参考文章:https://www.jianshu.com/p/3e0a399380df

在本App中AVAudioSession.sharedInstance()会使得其他App的背景音乐停止。应该本应用使用时候其他App背景音乐暂停,使用后恢复

1、可以在开启录音或播放时候

AVAudioSession.sharedInstance().setActive(true)

2、在录音完毕或播放完毕之后

AVAudioSession.sharedInstance().setActive(false, with: AVAudioSessionSetActiveOptions.notifyOthersOnDeactivation)

注意:如果使用AVCaptureSession的startRunning,使用完成后要主动调用stopRunning。不然setActive为false会报错:

[AVAudioSession setActive:withOptions:error:]: Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.

代码举例:

        var isOtherAudioPlaying: Bool = false
        
        //播放代码
        do {
            let player =  try AVAudioPlayer.init(contentsOf: url)
            //            player.delegate = self
            player.prepareToPlay()
            isOtherAudioPlaying = AVAudioSession.sharedInstance().isOtherAudioPlaying
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            player.play()
        } catch {
        }
//录音代码 do { let recorder = try AVAudioRecorder(url: url, settings: [AVFormatIDKey : NSNumber(value: kAudioFormatLinearPCM), AVSampleRateKey : 8000.0 as NSNumber, AVNumberOfChannelsKey : 1 as NSNumber, AVEncoderBitDepthHintKey : 16 as NSNumber, AVEncoderAudioQualityKey : AVAudioQuality.low.rawValue as NSNumber]) recorder.delegate = self // recorder.isMeteringEnabled = true if recorder.prepareToRecord() { isOtherAudioPlaying = AVAudioSession.sharedInstance().isOtherAudioPlaying try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord) try AVAudioSession.sharedInstance().setActive(true) if recorder.record(forDuration:Double(60)) { } else { print("Failed to record.") } } else { print("Failed to prepareToRecord.") } } catch { }
        //结束录音或播放之后
       guard isOtherAudioPlaying else {
return } do { try AVAudioSession.sharedInstance().setActive(false, with: AVAudioSessionSetActiveOptions.notifyOthersOnDeactivation) } catch {}