ios - Start playing an audio file when application goes in background -
it's "google maps" navigate in background.
i have added "app plays audio" "required background modes" already, doesn't work. what's wrong it?
here sample source code:
-(void)applicationdidenterbackground:(uiapplication *)application { uidevice* device = [uidevice currentdevice]; bool backgroundsupported = no; if ([device respondstoselector:@selector(ismultitaskingsupported)]) { backgroundsupported = device.multitaskingsupported; } if (backgroundsupported && _bgtask==uibackgroundtaskinvalid ) { uiapplication* app = [uiapplication sharedapplication]; dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ while (app.applicationstate==uiapplicationstatebackground && _bgtask!=uibackgroundtaskinvalid) { [nsthread sleepfortimeinterval:3]; [self playaudio]; } [app endbackgroundtask:_bgtask]; _bgtask = uibackgroundtaskinvalid; }); } } -(void)playaudio { [[avaudiosession sharedinstance] setcategory:avaudiosessioncategoryplayback error:nil]; [[avaudiosession sharedinstance] setactive: yes error: nil]; nsurl *audiofilelocationurl = [[nsbundle mainbundle] urlforresource:@"sound" withextension:@"caf"]; nserror *error; self.audioplayer = [[avaudioplayer alloc] initwithcontentsofurl:audiofilelocationurl error:&error]; [self.audioplayer setnumberofloops:-1]; self.audioplayer.delegate = self; [self.audioplayer preparetoplay]; [self.audioplayer play]; }
the url of audio file maybe web, , play multiple audio file in queue.
from apple's doc on subject:
because it's background tasks start in applicationdidenterbackground: not run until after method exits, should request additional background execution time before starting tasks. in other words, first call beginbackgroundtaskwithexpirationhandler: , run task on dispatch queue or secondary thread.
from own experience of playing background audio, if don't request time need set things beforehand [self.audioplayer play]
literally first line of code in applicationdidenterbackground
, otherwise system suspends app before audio has chance kick in , keep awake.