Search code examples
ioscordovaaudioplaybackstandby

Phonegap - play local audio when phone is locked iOS 6


I am building an app using PhoneGap that needs to be able to play local .mp3 files even though the phone is locked/standby. The audio player is build in HTML5, and is working fine, but the music stops when I either close the app or turn off the phone.

I tried following the answer given in this link UIWebView: HTML5 audio pauses in iOS 6 when app enters background

But no luck...

I did the import code at the top with the other import functions. 
And I also included the AVFoundation framework to my target. 

This is how the code looks in the AppDelegate.m

/**
 * This is main kick off after the app inits, the views and Settings are setup here. (preferred -iOS4 and up)
 */
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{

    /* THE GOOD STUFF */
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL ok;
    NSError *setCategoryError = nil;
    ok = [audioSession setCategory:AVAudioSessionCategoryPlayback
                         error:&setCategoryError];
    if (!ok) {
        NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
    }

I tried in simulator and on iPhone 5.

Is anyone able to help?


Solution

  • Firstly you have to set your audio category in your app_name-info.plist App Audio Category

    Then use the phonegap API media player http://docs.phonegap.com/en/2.7.0/cordova_media_media.md.html#media.play

    function playAudio(url) {
    // Play the audio file at url
    var my_media = new Media(url,
        // success callback
        function() {
            console.log("playAudio():Audio Success");
        },
        // error callback
        function(err) {
            console.log("playAudio():Audio Error: "+err);
    });
    
    // Play audio
    my_media.play({ playAudioWhenScreenIsLocked : true });
    

    Notice the playAudioWhenScreenIsLocked defaults to true anyways.

    Also note in the Simulator the Audio will never work in background, so you will need to test on a device.

    Please mark as Answered if this helped ?