Background music cancelled when capturing audio in AVCaptureSession

332 Views Asked by At

I would like background music to continue playing when I am inside my iOS app. However when ever I enter my app the background music is cancelled. I isolated the problem to the audio part of the AVCaptureSession:

var audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio);
var audioInput = AVCaptureDeviceInput.FromDevice(audioDevice);
captureSession.AddInput(audioInput);

I tried setting the AudioSession immediately after in two ways:

AudioSession.Initialize();
AudioSession.Category = AudioSessionCategory.AmbientSound;
AudioSession.SetActive(true);

or like this:

AudioSession.Initialize();
AudioSession.Category = AudioSessionCategory.MediaPlayback;
AudioSession.OverrideCategoryMixWithOthers = true;
AudioSession.SetActive(true);

But neither worked.

1

There are 1 best solutions below

0
Geir Smestad On BEST ANSWER

Have you tried explicitly creating an instance of the session object and setting MixWithOthers, as described here? I'm thinking the Xamarin equivalent would be something like

AVAudioSession session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.PlayAndRecord, AVAudioSessionCategoryOptions.MixWithOthers | AVAudioSessionCategoryOptions.DefaultToSpeaker);

Alternatively, as suggested in the link above, try setting the following in your AppDelegate:

AudioSession.Category = AudioSessionCategory.PlayAndRecord;
AudioSession.AudioShouldDuck = true;
AudioSession.OverrideCategoryDefaultToSpeaker = true;

...and then creating your AVCaptureSession like this:

AVCaptureSession session2 = new AVCaptureSession();
session2.AutomaticallyConfiguresApplicationAudioSession = false;