首页 > 解决方案 > 代表哪个告诉 Swift AvAudio 中是否播放了其他声音?

问题描述

我正在使用 AVAudioEngine 录制语音以将语音转换为文本,但如果用户手机突然开始播放音乐或铃声,我需要停止录制吗?是否有 AVAudio 代表告诉我何时播放其他音乐?

标签: swiftavfoundationavaudioengine

解决方案


假设您的 AVAudioSession 的类别是playback(默认类别),那么您可以订阅并接收此类中断的通知:

func setupNotifications() {
    let nc = NotificationCenter.default
    nc.addObserver(self,
                   selector: #selector(handleInterruption),
                   name: AVAudioSession.interruptionNotification,
                   object: AVAudioSession.sharedInstance)
}
@objc func handleInterruption(notification: Notification) {
    guard let userInfo = notification.userInfo,
        let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
        let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
            return
    }

    // Switch over the interruption type.
    switch type {

    case .began:
        // An interruption began. Update the UI as necessary.

    case .ended:
       // An interruption ended. Resume playback, if appropriate.

        guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return }
        let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
        if options.contains(.shouldResume) {
            // An interruption ended. Resume playback.
        } else {
            // An interruption ended. Don't resume playback.
        }

    default: ()
    }
}

相关文档


推荐阅读