objective c - Audio playing while app in background iOS -
i have app based around core bluetooth. when specific happens, app woken using core bluetooth background modes , fires off alarm, can't alarm working when app not in foreground.
i have alarm singleton class initialises avaudioplayer
this:
nsurl *url = [nsurl fileurlwithpath:[[nsbundle mainbundle] pathforresource:soundname oftype:@"caf"]]; self.player = [[avaudioplayer alloc] initwithcontentsofurl:url error:nil]; [[avaudiosession sharedinstance] setcategory:avaudiosessioncategoryplayback error:nil]; [[avaudiosession sharedinstance] setactive: yes error: nil]; [self.player preparetoplay]; self.player.numberofloops = -1; [self.player setvolume:1.0]; nslog(@"%@", self.player);
this method called when alarm code called:
-(void)startalert { nslog(@"%s", __function__); playing = yes; [self.player play]; nslog(@"%i", self.player.playing); if (vibrate) { [self vibratepattern]; } }
now when app in foreground, self.player.playing
returns 1
when app in background self.player.playing
returns 0
. why be? code being called, app awake , functioning. vibrate works uses audioservicesplaysystemsound(ksystemsoundid_vibrate);
any idea why sound won't play?
thanks
i have app needs background audio app works app background mode "voice on ip" needs record sometimes. play background audio telling app singleton need play audio in background:
uibackgroundtaskidentifier newtaskid = uibackgroundtaskinvalid; if([theplayer play]){ newtaskid = [[uiapplication sharedapplication] beginbackgroundtaskwithexpirationhandler:null]; }
edit: must call [[uiapplication sharedapplication] beginbackgroundtaskwithexpirationhandler:null];
before app goes background. in app, @ same time start playing, in yours, if player might started in background, should do:
- (void)applicationdidenterbackground:(uiapplication *)application{ // should retain newtaskid check background tasks , finish them newtaskid = [[uiapplication sharedapplication] beginbackgroundtaskwithexpirationhandler:null]; }
Comments
Post a Comment