一. AVAudioPlayer:
声明音乐控件AVAudioPlayer,必须声明为全局属性变量,否则可能不会播放,AVAudioPlayer只能播放本地音乐
//获取音乐文件路径 NSURL *soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:_fileName ofType:@"mp3"]]; if (!_BGMPlayer) { _asset = [[AVURLAsset alloc] initWithURL:soundUrl options:nil]; //实例化音乐播放控件 _BGMPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_asset.URL error:nil]; } if (_BGMPlayer != nil) { //缓冲播放 _BGMPlayer.delegate = self; [_BGMPlayer prepareToPlay]; _BGMPlayer.numberOfLoops = -1; [_BGMPlayer play]; }else{ NSLog(@"初始化失败"); }
二. AVURLAsset
创建一个由URL标识的代表任何资源的asset对象
_asset = [[AVURLAsset alloc] initWithURL:soundUrl options:nil]; //实例化音乐播放控件 _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_asset.URL error:nil];
三. AVAudioPlayerDelegate
/* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */ //产生中断后调用这个函数,通常暂停播放 - (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player { [self.playerpause]; } /* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */ /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */ //恢复中断后调用这个函数,继续播放 - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags { [self.playerplay]; } //解码出错后调用这个函数 - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error //播放结束后调用这个函数 - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
四. 参考链接
http://www.cnblogs.com/QianChia/p/5771149.html
http://www.jianshu.com/p/cc79c45b4ccf
http://www.360doc.com/content/15/1214/23/20918780_520470043.shtml
https://segmentfault.com/a/1190000004049416?_ea=471318