I want to configure AVAudioSession that I can record video with audio and also play music from Music app (or any other app that is producing sound, typically internet radios apps)
I configure session like this:
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: .mixWithOthers)
try? AVAudioSession.sharedInstance().setActive(true, with: .notifyOthersOnDeactivation)
This works the way that when my recording app is running I can start playing audio from music app and record video (also record audio as well). So far good.
Now, I put my recording app to the background. Music app continues to play. It is fine. But, when my app is coming back from background music app stop its playback. I would like it to continue. So it basically behaves as build in camera app when shooting video. Is there a way to tell the system that I want other app to continue playback?
I have almost met the similar problem and it is almost killed my one-two days for figure outing the problem.
In my case, I am used AVCaptureSession
for video/audio recording and it has property called automaticallyConfiguresApplicationAudioSession
. As per Apple docs
automaticallyConfiguresApplicationAudioSession: A Boolean value that indicates whether the capture session automatically changes settings in the app’s shared audio session.
The value of this property defaults to true, causing the capture session to automatically configure the app’s shared AVAudioSession instance for optimal recording
So If we are manually setting the AVAudioSession
, we should set this property as false
like below,
captureSession.automaticallyConfiguresApplicationAudioSession = false;
Making this property to false
and setting appropriate AVAudioSession
categories manually has solved my issue! Hope it will help in your case too!
Some more Observations on your code
.notifyOthersOnDeactivation
flag to activating an audio
session This flag is used only when deactivating your audio session. That is when you pass a value of false
in the beActive parameter of the setActive(_:options:)
instance method. So the below code fine for active a session
try? AVAudioSession.sharedInstance().setActive(true)
In default the AVAudioSessionCategoryPlayAndRecord
category leads
to a very low volume of background sound. If you want normal volume, need to use the option .defaultToSpeaker
with .mixWithOthers
as follows,
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.mixWithOthers, .defaultToSpeaker])
Oke! then I think It will now work fine if you have done all other stuff properly.
Note** I have created a working sample project for your reference and you can found it on GitHub Here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With