AVAudioPlayer音频播放
AVAudioPlayer类创建的实例可以看作为一个音频播放器,可以播放来自文件或存储的音频数据。
它支持多种音频格式,而且能够进行进度、音量、播放速度等控制。
使用这个类,可以:
1、在指定的时间开始播放音频
2、从文件或内存缓冲区播放音频
3、循环播放
属性 | 描述 |
@property(readonly, getter=isPlaying) BOOL playing | 是否正在播放,只读 |
@property float volume | 音量大小,范围0~1.0 |
@property float pan | 立体声,-1.0完全左声道,0.0左右声道平衡,1.0完全右声道 |
@property float rate | 播放速率,范围0.5~2.0,1.0时为正常播放,如果需要更改播放速率必须设置enableRate为YES |
@property BOOL enableRate | 是否可以更改播放速率 |
@property NSInteger numberOfLoops | 重复播放次数,为0时只播放一次,小于0时为无限播放,大于0时表示循环次数 |
@property(readonly) NSDictionary *settings | 音频播放次数信息,只读 |
@property(readonly) NSUInteger numberOfChannels | 与音频播放器相关联的声音通道的数量。(只读) |
@property(nonatomic, copy) NSArray *channelAssignments | 与音频播放器相关AVAudioSessionChannelDescription对象数组 |
@property(readonly) NSTimeInterval duration | 播放时长 |
@property NSTimeInterval currentTime | 当前播放时长 |
@property(readonly) NSTimeInterval deviceCurrentTime | 输出设备播放音频的时间,注意如果播放中被暂停此时间也会继续累加 |
@property(readonly) NSURL *url | 音频文件路径,只读 |
@property(readonly) NSData *data | 音频数据,只读 |
@property(getter=isMeteringEnabled) BOOL meteringEnabled | 否启用音频测量,默认为NO,一旦启用音频测量可以通过updateMeters方法更新测量值 |
对象方法 | 描述 |
- (instancetype)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError | 使用文件URL初始化播放器,注意这个URL不能是HTTP URL,AVAudioPlayer不支持加载网络媒体流,只能播放本地文件 |
- (instancetype)initWithData:(NSData *)data error:(NSError **)outError |
使用NSData初始化播放器,注意使用此方法时必须文件格式和文件后缀一致,否则出错,所以相比此方法更推荐使用上述方法 或- (instancetype)initWithData:(NSData *)data fileTypeHint:(NSString *)utiString error:(NSError **)outError方法进行初始化 |
- (BOOL)play | 播放音频文件 |
- (BOOL)playAtTime:(NSTimeInterval)time | 在指定的时间开始播放音频 |
- (void)pause | 暂停播放 |
- (void)stop | 停止播放 |
- (BOOL)prepareToPlay | 将音频文件加载到缓冲区 |
- (float)averagePowerForChannel:(NSUInteger)channelNumber | 获得指定声道的分贝平均值,注意如果要获得分贝平均值必须在此之前调用updateMeters方法 |
- (float)peakPowerForChannel:(NSUInteger)channelNumber | 获得指定声道的分贝峰值,注意如果要获得分贝峰值必须在此之前调用updateMeters方法 |
- (void)updateMeters | 更新音频测量值,注意如果要更新音频测量值必须设置meteringEnabled为YES,通过音频测量值可以即时获得音频分贝等信息 |
代理方法 | 说明 |
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag | 播放完成后调用,在这里可以进行一些属性的设置 |
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error | 音频解码发生错误 |
AVAudioPlayer的使用比较简单:
1、初始化AVAudioPlayer对象,通常指定本地文件路径
2、设置播放器属性,例如播放次数,音量大小,设置代理等
3、开始播放,调用play方法
下面就是AVAudioPlayer实现的一个简单播放器,它播放本地的音频文件,实现了播放、暂停、显示播放进度,现实播放时间等功能:
1 #import "JZViewController.h" 2 #import <AVFoundation/AVFoundation.h> 3 4 @interface JZViewController() <AVAudioPlayerDelegate> 5 6 @property (nonatomic, strong) AVAudioPlayer * audioPlayer; 7 @property (nonatomic, strong) UIImageView * imageView; 8 @property (nonatomic, strong) UIProgressView * progressView; 9 @property (nonatomic, strong) UILabel * timeLabel; 10 @property (nonatomic, strong) UILabel * currenttimeLabel; 11 @property (nonatomic, assign) NSTimer * timer; 12 @property (nonatomic, assign) int intTime; 13 @property (nonatomic, assign) int timeNum; 14 @property (nonatomic, assign) UIButton * button; 15 16 @end 17 18 @implementation JZViewController 19 20 - (void)viewDidLoad 21 { 22 [super viewDidLoad]; 23 self.title = @"礼物"; //播放音频为 礼物.mp3 钢琴曲 24 self.view.backgroundColor = [UIColor whiteColor]; 25 26 [self.view addSubview:self.imageView]; 27 28 [self initView]; 29 } 30 31 //界面初始化,添加一个view、一个进度条、3个label、一个button 32 - (void)initView 33 { 34 UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 150, [UIScreen mainScreen].bounds.size.width, 150)]; 35 view.backgroundColor = [UIColor colorWithRed:246 / 255.0 green:246 / 255.0 blue:246 / 255.0 alpha:0.9]; 36 view.alpha = 0.8f; 37 [self.view addSubview:view]; 38 39 UIProgressView * progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(40, 50, [UIScreen mainScreen].bounds.size.width - 80, 0)]; 40 self.progressView = progressView; 41 [view addSubview:progressView]; 42 43 UILabel * timeLabel = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 40, 40, 40, 20)]; 44 timeLabel.backgroundColor = [UIColor clearColor]; 45 timeLabel.font = [UIFont systemFontOfSize:11]; 46 timeLabel.textAlignment = NSTextAlignmentCenter; 47 self.timeLabel = timeLabel; 48 [view addSubview:timeLabel]; 49 50 UILabel * currentTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 40, 20)]; 51 currentTimeLabel.backgroundColor = [UIColor clearColor]; 52 currentTimeLabel.font = [UIFont systemFontOfSize:11]; 53 currentTimeLabel.textAlignment = NSTextAlignmentCenter; 54 self.currenttimeLabel = currentTimeLabel; 55 [view addSubview:currentTimeLabel]; 56 57 UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)]; 58 label.backgroundColor = [UIColor clearColor]; 59 label.text = @"礼物"; 60 label.textAlignment = NSTextAlignmentCenter; 61 [view addSubview:label]; 62 63 UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - 30, 70, 60, 60)]; 64 button.backgroundColor = [UIColor clearColor]; 65 [button setImage:[UIImage imageNamed:@"start.jpg"] forState:UIControlStateNormal]; 66 [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside]; 67 self.button = button; 68 button.tag = 10; 69 [view addSubview:button]; 70 } 71 72 //初始化imageView,添加背景图片 73 - (UIImageView *)imageView 74 { 75 if(!_imageView){ 76 UIImage * image = [UIImage imageNamed:@"sjz.jpg"]; 77 UIImageView * imageView = [[UIImageView alloc] initWithImage:image]; 78 imageView.frame = [UIScreen mainScreen].bounds; 79 _imageView = imageView; 80 } 81 return _imageView; 82 } 83 84 //懒加载,创建audioPlayer 85 - (AVAudioPlayer *)audioPlayer 86 { 87 if(!_audioPlayer){ 88 NSString * urlStr = [[NSBundle mainBundle] pathForResource:@"礼物.mp3" ofType:nil]; 89 NSURL * url = [NSURL fileURLWithPath:urlStr]; 90 NSError * error = nil; 91 _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 92 //设置播放属性 93 _audioPlayer.numberOfLoops = 0; 94 _audioPlayer.delegate = self; 95 [_audioPlayer prepareToPlay]; //加载音频文件到缓存 96 97 98 if(error){ 99 NSLog(@"初始化播放器过程发生错误,错误信息:%@", error.localizedDescription); 100 return nil; 101 } 102 103 } 104 return _audioPlayer; 105 } 106 107 //点击button后调用的方法,播放、暂停音乐 108 - (void)clickButton:(UIButton *)sender 109 { 110 if(sender.tag == 10){ 111 sender.tag = 20; 112 [sender setImage:[UIImage imageNamed:@"stop.jpg"] forState:UIControlStateNormal]; 113 [self.audioPlayer play]; 114 self.timer.fireDate = [NSDate distantPast]; 115 }else{ 116 sender.tag = 10; 117 [sender setImage:[UIImage imageNamed:@"start.jpg"] forState:UIControlStateNormal]; 118 [self.audioPlayer pause]; 119 self.timer.fireDate = [NSDate distantFuture]; 120 } 121 } 122 123 //初始化定时器 124 - (NSTimer *)timer 125 { 126 if(!_timer){ 127 _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimeAddProgress) userInfo:nil repeats:YES]; 128 self.timeNum = (int)self.audioPlayer.duration; 129 } 130 return _timer; 131 } 132 133 //定时器的调用方法,在这里更新进度条,并且更新时间 134 - (void)updateTimeAddProgress 135 { 136 float progress = self.audioPlayer.currentTime / self.audioPlayer.duration; 137 [self.progressView setProgress:progress animated:YES]; 138 139 self.intTime++; 140 NSString * str = [NSString stringWithFormat:@"%.2d:%.2d", self.intTime / 60, self.intTime % 60]; 141 self.currenttimeLabel.text = str; 142 143 self.timeNum--; 144 NSString * strTime = [NSString stringWithFormat:@"%.2d:%.2d", self.timeNum / 60, self.timeNum % 60]; 145 self.timeLabel.text = strTime; 146 } 147 148 //代理方法,做一些播放完成后的处理,删除掉定时器,button图片的更改、停止音乐播放等 149 - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 150 { 151 self.intTime = 0; 152 [self.audioPlayer stop]; 153 [self.timer invalidate]; 154 self.timer = nil; 155 156 self.button.tag = 10; 157 [self.button setImage:[UIImage imageNamed:@"start.jpg"] forState:UIControlStateNormal]; 158 } 159 160 @end