方式一1:
NSURL * url = [[NSBundle mainBundle] URLForResource:@"mmusic" withExtension:@".mp3"];
AVPlayerItem * songItem = [[AVPlayerItem alloc]initWithURL:url];
self.PlayBgMp3Player = [[AVPlayer alloc]initWithPlayerItem:songItem];
//AVPlayer * player = [[AVPlayer alloc] initWithURL:url];
//AVPlayerItem * songItem = player.currentItem;
[self.PlayBgMp3Player play];
方式2:
NSURL *fileURL = [[NSBundle mainBundle]URLForResource:@"mmusic" withExtension:@"mp3"];
// 2.建立 AVAudioPlayer 對象
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
// 3.列印歌曲資訊
NSString *msg = [NSString stringWithFormat:@"音頻檔案聲道數:%ld\n 音頻檔案持續時間:%g",self.audioPlayer.numberOfChannels,self.audioPlayer.duration];
NSLog(@"%@",msg);
// 4.設定循環播放
self.audioPlayer.volume = 1.0;
self.audioPlayer.numberOfLoops = -1;
// 5.開始播放
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
播放不出來:需要在兩種方式代碼之前,加上:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
并且需要在target->capabilities->Background Modes,對第一個,就是audio,airplay那一個打溝。