Use AVAudioPlayer in OperationQueue

业务需求要提供一些ringtone供用户选择并且设置为来电铃声.这样就会涉及到预览ringtone.这边预览ringtone选择用AVAudioPlayer去播放.选择AVAudioPlayer的原因是AVAudioPlayer可控性比较大,可以播放,暂停,恢复播放等.使用AudioToolbox提供的api也能播放ringtone当是不能满足操作需求,暂停,恢复,故排除AudioToolbox.

要使用AVAudioPlayer播放ringtone必然会涉及到AVAudioSession.AVAudioSession简而言之: 音频会话,主要用来管理音频设置与硬件交互.关于AVAudioSession`详细的信息读者可自行去查.播放一个ringtone的简化流程代码大概如下:

try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord)

try? AVAudioSession.sharedInstance().setActive(true, options: [])

let audioPlayer = try? AVAudioPlayer(contentsOf: ringtoneUrl)

audioPlayer?.play()
为了不卡UI一般会放到子线程中去播放:

DispatchQueue.global().async {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord)
            
try? AVAudioSession.sharedInstance().setActive(true, options: [])
            
let audioPlayer = try? AVAudioPlayer(contentsOf: ringtoneUrl)
            
audioPlayer?.play()
}

看似一切正常,但是当你频繁的点击切换ringtone,变成开始,结束,暂停。这样会导致播放失败又有多线程竞争音频资源的问题,并且在iOS10.x上会crash,因为音频资源不可能切换太快.并且快速切换也会开启多个子线程,这是没必要的.一般来说一个设计合理的app同一时刻只会有一个音频在播放.所以我们只需要一个线程专门控制音频播放即可,这里推荐Queue来控制,因为Queue api比较友好,并且比较可控.
//作为一个对象的变量比较好,因为会多次点击播放,这样用同一个queue管理.
lazy var ringToneQueue: OperationQueue = {
    let ringToneQueue = OperationQueue()
    ringToneQueue.name = "rc.ringtone.queue"
    ringToneQueue.maxConcurrentOperationCount = 1
    return ringToneQueue
}()


//回收资源
if self.ringToneQueue.operationCount > 0 {
   self.ringToneQueue.cancelAllOperations()
}

self.ringToneQueue.addOperation({
    //播放ringtone
})


根据业务需求我这边是把包装AVAudioPlayer成一个单例,不会多次创建AVAudioPlayer。

internal class AudioPlayerManager : NSObject {

    internal static let shared: AudioPlayerManager

    internal var currentTime: TimeInterval? { get set }

    internal var audioFilePath: String? { get }

    internal var isPlaying: Bool { get }

    internal var delegates: <<error type>>

    override internal init()

    internal func setCategory(category: AVAudioSession.Category, options: AVAudioSession.CategoryOptions, shouldSetPlayBack: Bool = true) throws

    /**
     * Prepare some configuration for AudioPlayer.
     * Call this method to configurate AudioPlayer and than call `play(atTime time: TimeInterval? = nil)` to play audio.
     *
     */
    internal func configAudioPlayer(with audioFilePath: String, configAudioPlayerClosure: ((Bool, Error?) -> Void)?)

    /**
     *
     * Call this method after call `configAudioPlayer(with audioFilePath: String, configAudioPlayerClosure: ((AVAudioPlayer?) -> Void)?)`.
     *
     */
    internal func play(category: AVAudioSession.Category = .playAndRecord, options: AVAudioSession.CategoryOptions = [.defaultToSpeaker], portOverride: AVAudioSession.PortOverride = .none) throws

    internal func play(audioFilePath: String, category: AVAudioSession.Category = .playAndRecord, options: AVAudioSession.CategoryOptions = [.defaultToSpeaker], atTime time: TimeInterval? = nil, portOverride: AVAudioSession.PortOverride = .none) throws

    internal func stop(options: AVAudioSession.SetActiveOptions = [.notifyOthersOnDeactivation])

    internal func pause(options: AVAudioSession.SetActiveOptions = [.notifyOthersOnDeactivation])

    internal func resume()

    internal func setAudioSessionActive(isActive: Bool, options: AVAudioSession.SetActiveOptions = [])
}

这样播放的代码大概是这样:

//回收资源
if self.ringToneQueue.operationCount > 0 {
   self.ringToneQueue.cancelAllOperations()
}

self.ringToneQueue.addOperation({
    //播放ringtone
    if !AudioPlayerManager.shared.isPlaying {
       AudioPlayerManager.play(audioFilePath: selectedTonePath)
    } else {
       if let path = AudioPlayerManager.audioFilePath, path == selectedTonePath {
          AudioPlayerManager.stop()
        } else {
          AudioPlayerManager.play(audioFilePath: selectedTonePath)
        }
    }
})

推荐阅读更多精彩内容