iOS播放音频

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 也是会造成初始化失败的)

参考:

参考文档一

参考文档二

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容