Play music in the background of iOS
Blog Category:
http://www.apple.com.cn/developer/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ Audioandvideotechnologies/audioandvideotechnologies.html#//apple_ref/doc/uid/tp40007072-ch19-sw32
1. First import the frame used to play the music in the Project: AV Foundation framework
2. Add code to the project:
Import Frame Header file:
Java code
- #Import <AVFoundation/AVFoundation.h>
To define a player variable:
Java code
- Avaudioplayer *player;
- @property (Strong, nonatomic) Avaudioplayer *player;
To customize the playback method:
Java code
- -(void) playsound{
- [[Avaudiosession sharedinstance] Setcategory:avaudiosessioncategoryplayback Error:nil];
- [[Avaudiosession sharedinstance] Setactive:yes Error:nil];
- NSString *soundfilepath =
- [[NSBundle Mainbundle] Pathforresource: @"sound" OfType: @"MP3"];
- Nsurl *fileurl = [[Nsurl alloc] initfileurlwithpath:soundfilepath];
- Self.player = [[Avaudioplayer alloc] Initwithcontentsofurl:fileurl Error:nil];
- [FileURL release];
- [Player play];
- [Player Setdelegate:self];
- }
Press the home key to pause playback (APPDELEGATE.M):
Java code
- -(void) Applicationdidenterbackground: (uiapplication *) Application
- {
- if (self.player.playing) {
- [Self.player pause];
- }
- }
Run the software to continue playback (APPDELEGATE.M):
Java code
- -(void) Applicationwillenterforeground: (uiapplication *) Application
- {
- if (self.player.playing = = NO) {
- [Self.player play];
- }
- }
Java code
- Simulator can be tested!
Play music in the background of iOS