標籤:
音頻播放
1、介紹
- 功能介紹
用於播放比較長的音頻、說明、音樂 ,使用到的是AVFoundation
- 架構介紹
* AVAudioPlayer
* 初始化:
注意 :
(3)必須聲明全域變數的音樂播放對象、或者是屬性的音樂播放對象 才可以播放
(4)在退出播放頁面的時候 一定要把播放對象置空 同時把delegate置空
匯入架構:#import <AVFoundation/AVFoundation.h>
聲明全域變數
@interface ViewController ()<AVAudioPlayerDelegate>{ AVAudioPlayer *audioPlayer;}@end
音訊基本屬性
預播放 [audioPlayer prepareToPlay];
擷取 當前音樂的聲道 audioPlayer.numberOfChannels
audioPlayer.currentTime //當前播放的時間
audioPlayer.playing//判斷是否現正播放
audioPlayer.numberOfLoops ;//設定迴圈播放的此次
audioPlayer.duration 獲得播放音訊時間
audioPlayer.pan 設定左右聲道效果
audioPlayer.volume 設定音量 0.0- 1.0 是一個百分比
//設定速率 必須設定enableRate 為YES; audioPlayer.enableRate =YES; audioPlayer.rate =3.0;
音量 audioPlayer.volume = 0.1;
設定播放次數 負數是無限迴圈的 0 是一次 1是兩次 依次類推 audioPlayer.numberOfLoops = 0;
獲得當前峰值 audioPlayer peakPowerForChannel:2
平均峰值
audioPlayer averagePowerForChannel:2
音頻播放的幾個代理方法
//播放完成的時候調用- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{ NSLog(@"播放完成");}//解碼出現錯誤的時候調用- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{}//開始被打擾中斷的時候調用- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{ }//中斷結束後調用- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{ }
執行個體解析音頻播放
初始化一個按鈕
在ViewDidLoad中
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(100, 100, 100, 100); button.backgroundColor = [UIColor brownColor]; [button setTitle:@"Play" forState:UIControlStateNormal]; [button setTitle:@"Pause" forState:UIControlStateSelected]; [button addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; [self playMusicWithName:@"TFBOYS-青春修鍊手冊.mp3"];
按鈕的觸發方法:
- (void)play:(UIButton *)sender{
sender.selected = !sender.selected;
sender.selected != YES ? [audioPlayer pause]:[audioPlayer play];
}
- (void)playMusicWithName:(NSString *)name{ NSError *error; // 建立一個音樂播放對象 audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:name withExtension:nil] error:&error]; if (error) { NSLog(@"%@",error); } 預播放 [audioPlayer prepareToPlay]; 播放 在這裡不寫在這 但它是必須的步驟 [audioPlayer play]; 擷取 當前音樂的聲道 NSLog(@"%ld",audioPlayer.numberOfChannels); durtion:獲得播放音訊時間 設定聲道 -1.0左 0.0中間 1.0右 audioPlayer.pan = 0.0; 音量 audioPlayer.volume = 0.1; 設定速率 必須設定enableRate為YES audioPlayer.enableRate = YES; 設定速率 0.5是一半的速度 1.0普通 2.0雙倍速率 audioPlayer.rate = 1.0; currentTime 獲得時間 獲得峰值 必須設定meteringEnabled為YES audioPlayer.meteringEnabled = YES; 更新峰值 [audioPlayer updateMeters]; 獲得當前峰值 NSLog(@"當前峰值:%f",[audioPlayer peakPowerForChannel:2]); NSLog(@"平均峰值%f",[audioPlayer averagePowerForChannel:2]); 設定播放次數 負數是無限迴圈的 0 是一次 1是兩次 依次類推 audioPlayer.numberOfLoops = 0; 掛上代理 audioPlayer.delegate = self; }
iOS開發之 音頻播放