I have a video capturing app and I want to be able to play background music while recording audio+video.
I can accomplish this if I set the AVAudioSession
category to PlayAndRecord
in didFinishLaunchingWithOptions
. However, this causes a glitch in the audio whenever the view with the camera enters or exits the foreground, and its apparently impossible to get rid of: https://forums.developer.apple.com/message/74778#74778
I can live with the glitch if it just happens when I start/stop recording video, but that means I need to change the AVAudioSession
category from Ambient
to PlayAndRecord
when a button is pressed, and this also seems to not be possible.
How do I change the AVAudioSession
category?
I tried this:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionMixWithOthers
error:nil];
But the background music stops when the recording starts.
Following this post: AVCaptureSession and background audio iOS 7
I tried deactivating the session then setting the category:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
[session setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDefaultToSpeaker
error:nil];
[session setActive:YES error:&error];
I also tried listening for the AVAudioSessionRouteChangeNotification
and setting the category in that handler after deactivating the session. But the background music always turns off when the app starts recording.
Why can't I change the AVAudioSession
category?
Please try this category
AVAudioSessionCategoryMultiRoute
or check both categories AVAudioSessionCategoryPlayAndRecord | AVAudioSessionCategoryRecord
来源:https://stackoverflow.com/questions/35615707/avaudiosession-setcategory-not-working