利用AVFoundation库中的AVAudioPlayer类实现简单的音乐播放:
核心代码:
NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:path];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if([UIApplication sharedApplication].applicationState== UIApplicationStateBackground) {
NSLog(@"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx后台播放");
[_player play];
UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier newTask = [app beginBackgroundTaskWithExpirationHandler:nil];
if(bgTask!= UIBackgroundTaskInvalid) {
[app endBackgroundTask: bgTask]; } bgTask = newTask; }
else{
NSLog(@"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx前台播放");
[_player prepareToPlay];
[_player setVolume:1];
_player.numberOfLoops = 1; //设置音乐播放次数 -1为一直循环
[_player play]; //播放 }