1.播放網(wǎng)絡(luò)音頻
NSURL * url =[NSURL URLWithString:MP3URL];
AVPlayerItem* songItem =[[AVPlayerItem alloc]initWithURL:url];
self.avplayer=[[AVPlayer alloc]initWithPlayerItem:songItem];
[self.avplayer play];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished) name:AVPlayerItemDidPlayToEndTimeNotificationobject:songItem];
2.播放本地音頻
NSString *tmp=[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"audio/move.mp3"];
NSLog(@"%@",tmp);
NSURL*moveMP3=[NSURL fileURLWithPath:[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"audio/move.mp3"]];
NSError*err=nil;
self.movePlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:moveMP3 error:&err];
self.movePlayer.volume=1.0;
[self.movePlayer prepareToPlay];if(err!=nil) {
NSLog(@"move player init error:%@",err);
}else{
[self.movePlayer play];
注意:
1.兩種方法player必須是全局的,否則播放沒有聲音。
2.本地音樂文件是否存在薇正,路徑是否正確;
3.初始化NSURL時囚衔,是否使用的是 fileURLWithPath . (如果錯用URLWithString 也是會造成初始化失敗的)
參考:
作者:weicyNO_1
鏈接:http://www.reibang.com/p/54281ed58536
來源:簡書
著作權(quán)歸作者所有挖腰。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處练湿。
注意在請求數(shù)據(jù)和頁面即將消失時猴仑,停止播放
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[self.avplayer pause];
[self playbackFinished];
}
iOS 使用AVPlayer自定義的播放器,當(dāng)手機(jī)在靜音模式播放器也靜音的解決方法肥哎!
在appdelegate中添加一下代碼辽俗,可解決手機(jī)在靜音模式播放器也靜音的問題!
AVAudioSession *avSession = [AVAudioSessionsharedInstance];
[avSession setCategory:AVAudioSessionCategoryPlaybackerror:nil];
[avSession setActive:YESerror:nil];