【问题标题】:AVAudioEngine recording microphone input seems to stop upon playing musicAVAudioEngine 录制麦克风输入似乎在播放音乐时停止
【发布时间】:2021-07-10 16:59:58
【问题描述】:

我正在录制麦克风输入以将其与 Shazam 目录中的歌曲相匹配。这行得通,但是如果我start() AVAudioEngine 然后发生一些事情,比如通过MPMusicPlayerController.applicationMusicPlayer.play() 开始播放音乐,音频引擎似乎停止或被中断。麦克风录音关闭,因此SHSessionDelegate 永远找不到匹配项或因错误而失败,因此我的 UI 卡住了,显示它正在收听,而不再显示它正在收听。有没有办法在发生这种情况时得到通知,以便我可以更新 UI 以处理取消?

private lazy var shazamAudioEngine = AVAudioEngine()
private lazy var shazamSession: SHSession = {
    let session = SHSession()
    session.delegate = self
    return session
}()

...

try? AVAudioSession.sharedInstance().setCategory(.record)

//Create an audio format for our buffers based on the format of the input, with a single channel (mono)
let audioFormat = AVAudioFormat(standardFormatWithSampleRate: shazamAudioEngine.inputNode.outputFormat(forBus: 0).sampleRate, channels: 1)

//Install a "tap" in the audio engine's input so that we can send buffers from the microphone to the session
shazamAudioEngine.inputNode.installTap(onBus: 0, bufferSize: 2048, format: audioFormat) { [weak self] buffer, when in
    //Whenever a new buffer comes in, we send it over to the session for recognition
    self?.shazamSession.matchStreamingBuffer(buffer, at: when)
}

do {
    try shazamAudioEngine.start()
} catch {
    ...
}

【问题讨论】:

    标签: ios avfoundation avaudioengine shazam


    【解决方案1】:

    在我的测试中,isRunning 跟踪此状态,因此当您开始播放音乐并且麦克风停止录制时,它会从 true 变为 false。不幸的是,KVO 无法观察到该属性,所以我所做的是设置一个重复的 Timer 来检测它是否会更改以处理取消,确保在发生其他状态更改时使用定时器 invalidate()

    audioEngineRunningTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] timer in    
        //the audio engine stops running when you start playing music for example, so handle cancelation here
        if self?.shazamAudioEngine.isRunning == false {
            //...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-04
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多