【问题标题】:How to play and listen to audio at the same time using AVAudioSession如何使用 AVAudioSession 同时播放和收听音频
【发布时间】:2022-08-04 12:30:10
【问题描述】:

我正在使用标准代码开始收听麦克风并使用 SHSession 委托检测带有 ShazamKit 的歌曲。

let audioSession = AVAudioSession.sharedInstance()
audioSession.requestRecordPermission { isGranted in
    guard isGranted else { return }
    try? audioSession.setActive(true, options: .notifyOthersOnDeactivation)
    let inputNode = self.audioEngine.inputNode
    let recordingFormat = inputNode.outputFormat(forBus: 0)
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) {
        (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
        self.session.matchStreamingBuffer(buffer, at: nil)
    }
    self.audioEngine.prepare()
    do {
        try self.audioEngine.start()
    } catch (let error) {
        assertionFailure(error.localizedDescription)
    }
}

当通过收听一些外部声源(如音乐栏)进行歌曲检测时,一切正常。但我需要提供机会从另一个应用程序(例如 Soundcloud)打开一些歌曲,打开我的应用程序并检测它。但是,如果执行此代码块,歌曲播放就会停止。我试图通过 setCategory 方法更改总线值、缓冲区大小、添加一些类别,但没有任何帮助。正如我所建议的,问题可能是由使用相同的资源(如总线)引起的,但正如我已经提到的,我试图改变这个值

  • 您需要使用.mixWithOthers 设置您的音频会话类别,然后激活它

标签: swift avfoundation


【解决方案1】:

使用选项.mixWithOthers 允许全音量背景音频。

或使用选项.duckOthers 以降低背景音频的音量。

let audioSession = AVAudioSession.sharedInstance()
do {
  try audioSession.setCategory(.playAndRecord, mode: .default, options: [.mixWithOthers])
  try audioSession.setActive(true)
} catch {
  print("Unable to activate audio session: \(String(describing: error))")
}

// ..later, when ready to deactivate:
do {
  try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
} catch {
  print("Unable to deactivate audio session: \(String(describing: error))")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多