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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM