1.播放网络音频
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
链接:https://www.jianshu.com/p/54281ed58536
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
注意在请求数据和页面即将消失时,停止播放
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[self.avplayer pause];
[self playbackFinished];
}
iOS 使用AVPlayer自定义的播放器,当手机在静音模式播放器也静音的解决方法!
在appdelegate中添加一下代码,可解决手机在静音模式播放器也静音的问题!
AVAudioSession *avSession = [AVAudioSessionsharedInstance];
[avSession setCategory:AVAudioSessionCategoryPlaybackerror:nil];
[avSession setActive:YESerror:nil];
网友评论