利用AVFoundation庫中的AVAudioPlayer類實(shí)現(xiàn)簡單的音樂播放:
核心代碼:
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; //設(shè)置音樂播放次數(shù) -1為一直循環(huán)
[_player play]; //播放 }