1, Step one: in Info.plist, add "Required background Modes" key, value is: App plays audio
Or:
Step Two:
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions
{
self.window = [[[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]] autorelease ];
//Override point for customization after application launch.
nserror *setcategoryerr = nil;
nserror *activationerr = nil;
[[avaudiosession sharedinstance]
setcategory: Avaudiosessioncategoryplayback
Error: &setCategoryErr];
[[avaudiosession sharedinstance]
setactive:yes
Error: &activationErr];
self.window.backgroundColor = [Uicolor Whitecolor];
[Self.window makekeyandvisible];
return YES;
}
Step Three: Add the following code to the Appdelegate file-(void) Applicationdidenterbackground: (uiapplication *) application function, You can also add to the notification method after the app is registered in a specific class to enter the background
-(void) Applicationdidenterbackground: (uiapplication *) application{
uiapplication* app = [UIApplication sharedapplication];
__block Uibackgroundtaskidentifier Bgtask;
Bgtask = [App beginbackgroundtaskwithexpirationhandler:^{
Dispatch_async (Dispatch_get_main_queue (), ^{
if (bgtask! = uibackgroundtaskinvalid)
{
Bgtask = Uibackgroundtaskinvalid;
}
});
}];
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
Dispatch_async (Dispatch_get_main_queue (), ^{
if (bgtask! = uibackgroundtaskinvalid)
{
Bgtask = Uibackgroundtaskinvalid;
}
});
});
}
The next step is to play the playback page:
Join the agent first:avaudioplayerdelegate
//read the audio file from the Budle path the filename is your song name, MP3 is your audio formatNSString *string= [[NSBundle mainbundle] Pathforresource:@"Has_consult"OfType:@"mp3"]; //convert audio files to URL formatNsurl *url = [Nsurl Fileurlwithpath:string]; //Initialize the audio class and add playback filesNserror *error; Avaudioplayer= [[Avaudioplayer alloc] Initwithcontentsofurl:url error:&ERROR]; //set Initial volume size//avaudioplayer.volume = 1; //set the number of music plays-1 to keep loopingAvaudioplayer.numberofloops =-1; //Pre-play[Avaudioplayer Preparetoplay]; NSLog (@"%ld",(Long) error.code);//Play-(void) play{[Avaudioplayer play]; }//Stop-(void) stop{Avaudioplayer.currenttime=0;//The current playback time is set to 0[Avaudioplayer stop]; }
IOS to play back music sound avaudioplayer