AVAudioPlayer播放本地音频
AVAudioPlayer苹果官方上说一般用于播放本地音频,不能用于播放网络上的音频。
具体的代码:
先导入
#import <AVFoundation/AVFoundation.h>
//本地音频的路径
NSString * path = [[NSBundle mainBundle] pathForResource:@"aaa.mp3" ofType:nil] ;
NSError * error = nil;
self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
self.player.delegate = self;
//音量,值在0-1之间
self.player.volume = 1.0;
player.currentTime = 15.0;//可以指定从任意位置开始播放
player.numberOfLoops = 3;//默认只播放一次
// [self.player prepareToPlay];
//只写上面那一句是不会播放的,这一句是必须写的
[self.player play];
//[self.player pause] 暂停播放
可以在 AVAudioPlayerDelegate 代理方法中监听播放的状态
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"结束播放");
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
NSLog(@"出错了");
}
- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player
{ //处理中断的代码
}
- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player
{
//处理中断结束的代码
}
需要注意的一点是,AVAudioPlayer需要设置一个强引用的属性,否则播放是没有声音的。