Max
Max

Reputation: 53

How to play and listen to audio at the same time using AVAudioSession

I'm using standard code to start listening to microphone and using SHSession delegate detect song with 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)
    }
}

Everything works fine when song detection is happening by listening to some external sound sources like music column. But I need to provide opportunity to turn on some song from another app (Soundcloud for example), open my app and detect it. But when this block of code if executed, song playing stops. I tried to change bus value, buffer size, add some categories via setCategory method but nothing helps me. As I suggest, issue might be caused by using the same resources like bus, but as I already mentioned, I tried to change this value

Upvotes: 0

Views: 661

Answers (1)

kwiknik
kwiknik

Reputation: 885

Use option .mixWithOthers to allow background audio at full volume.

Or use option .duckOthers to allow background audio at reduced volume.

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))")
}

Upvotes: 1

Related Questions