Search code examples
iosaudioavfoundationios-camera

iOS: Play music from another app while camera is open and taking a picture


I checked Google and here as well. Maybe the question hasn't been asked yet or I am just asking it in a very weird way. There are certain apps, one that I've noticed in particular is Snapchat, where when the app opens, the music continues to play even with the camera and even while taking a picture with silent switch turn on or off. The camera sound goes off as well.

So for an example, right now I am listening to music through Soundcloud and when I open my app, the music stops playing, but I can press play and continue to play music while using my app once I put this line of code in my appWillEnterForeground method: [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];

When I do this in Snapchat, the music continues to play. Even when I take a video too!

How?


Solution

  • There has to be some code that uses the AV system for audio in the way. Check for a call like

    [session addInput:audioDeviceInput];
    

    where session is an instance of AVCaptureSession.

    To demonstrate and research, you can take the Apple example AVCam (https://developer.apple.com/library/ios/samplecode/AVCam/Introduction/Intro.html) and run it from XCode. When music is playing, it will stop playing when the AVCam app starts.

    Now open the source file AVCam/AVCamViewController.m and search for the line

    [session addInput:audioDeviceInput];
    

    When you delete this line or comment it out, music will continue to play when you run the app.

    Off course, there may be other statements that block the sound playing in your app. Check calls to methods from AV objects and look especially for audio input and output.