iOS开发 AVAudioPlayer
簡述
AVAudioPlayer 是一個屬于 AVFoundation.framework 的一個類,它的功能類似于一個功能強大的播放器,AVAudioPlayer 支持廣泛的音頻格式,主要是以下這些格式。
- AAC
- AMR (Adaptive multi-Rate,一種語音格式)
- ALAC (Apple lossless Audio Codec)
- iLBC (internet Low Bitrate Codec,另一種語音格式)
- IMA4 (IMA/ADPCM)
- linearPCM (uncompressed)
- u-law 和 a-law
- MP3 (MPEG-Laudio Layer 3)
AVAudioPlayer 的使用
AVAudioPlayer 初始化
AVAudioPlayer方法調用
使用 AVAudioPlayer 讀取音頻信息
代理方法
代碼
AVAudioPlayer 初始化
首先導入兩首格式為 mp3 的歌曲,再導入歌手圖片
在 ViewController.h 導入
#import <AVFoundation/AVFoundation.h> #import <MediaPlayer/MediaPlayer.h> 復制代碼然后必須持有一個 AVAudioPlayer 對象,若此對象不是屬性,則無法播放
@property (nonatomic , strong) AVAudioPlayer *player; 復制代碼添加控件如圖所示,給控件命名
獲取制定 url 對象
NSURL *url = [[NSBundle mainBundle] URLForResource:@"吳亦凡-時間煮雨" withExtension:@"mp3"]; 復制代碼初始化 AVAudioPlayer 對象
self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil]; 復制代碼設置代理
self.player.delegate = self; 復制代碼這樣就播放器就初始化完成了
將storyboard里面 開始 按鈕綁定 - (IBAction)start:(id)sender 方法
- (IBAction)start:(id)sender {if ([self.player isPlaying]) {[self.startBtn setBackgroundImage:[UIImage imageNamed:@"播放"] forState:0];[self.player pause];}else{[self.startBtn setBackgroundImage:[UIImage imageNamed:@"暫停"] forState:0];[self.player play];}if (_timer == nil) {_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];}} 復制代碼注: 上訴代碼中定義了一個 NSTimer 變量,因為播放器沒有播放進程的委托,所以只能自定義NSTimer變量對播放器進行監控
@property (strong, nonatomic) NSTimer *timer; 復制代碼將storyboard里面 停止 按鈕綁定 - (IBAction)stop:(id)sender 方法
- (IBAction)stop:(id)sender {[self.player stop];//計時器停止[_timer invalidate];//釋放定時器_timer = nil; } 復制代碼設置剛才綁定的定時器調用方法updateProgress
-(void)updateProgress{//進度條顯示播放進度self.progress.progress = self.player.currentTime/self.player.duration;self.info1.text = [NSString stringWithFormat:@"當前播放時間%f",self.player.currentTime]; } 復制代碼實現 AVAudioPlayer 的委托方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{if (player == _player && flag) {[self.startBtn setBackgroundImage:[UIImage imageNamed:@"播放"] forState:0];} } -(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{if (player == _player){NSLog(@"播放被中斷");} }復制代碼此時,音樂就可以播放了!!!
但是,人們使用音樂大都是后臺播放,那么如何添加后臺播放支持呢?
后臺播放
在項目里 info.plist 右鍵 open As -- source code 添加代碼:
<key>UIBackgroundModes</key><array><string>audio</string></array> 復制代碼同樣,代碼里面也要添加后臺播放支持
//設置鎖屏仍能繼續播放 [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil]; 復制代碼這樣 音樂在后臺就可以播放了!!
那么很多播放器都有一個功能,那就是在用戶拔掉耳機的時候,暫停播放
監聽播放設備
//添加通知,拔出耳機后暫停播放 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];/*** 一旦輸出改變則執行此方法** @param notification 輸出改變通知對象*/ -(void)routeChange:(NSNotification *)notification{NSDictionary *dic=notification.userInfo;int changeReason= [dic[AVAudioSessionRouteChangeReasonKey] intValue];//等于AVAudioSessionRouteChangeReasonOldDeviceUnavailable表示舊輸出不可用if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {AVAudioSessionRouteDescription *routeDescription=dic[AVAudioSessionRouteChangePreviousRouteKey];AVAudioSessionPortDescription *portDescription= [routeDescription.outputs firstObject];//原設備為耳機則暫停if ([portDescription.portType isEqualToString:@"Headphones"]) {[self.player pause];}} } 復制代碼這樣就能在拔掉耳機的時候,暫停播放了!!!
但是似乎還是差了一些什么,好像鎖屏界面空空如也啊!!!
定制鎖屏界面
設置后臺播放時顯示的東西,例如歌曲名字,圖片等
要用到 <MediaPlayer/MediaPlayer.h> 這個庫,剛才已經導入過
- (void)setPlayingInfo {// 設置后臺播放時顯示的東西,例如歌曲名字,圖片等MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"吳亦凡.jpg"]];NSDictionary *dic = @{MPMediaItemPropertyTitle:@"時間煮雨",MPMediaItemPropertyArtist:@"吳亦凡",MPMediaItemPropertyArtwork:artWork};[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dic]; } 復制代碼這樣,圖片就在鎖屏界面顯示了,不過,鎖屏界面上面的三個按鈕,怎么控制播放呢!!
接收鎖屏歌曲按鈕控制 (上一首,播放,下一首)
首先,你要在一個繼承 UIResponder 類里面接收遠程控制,本文以 ViewController 為例
添加如下代碼,接受遠程控制和取消遠程控制。
- (void)viewDidAppear:(BOOL)animated {// 接受遠程控制[self becomeFirstResponder];[[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; }- (void)viewDidDisappear:(BOOL)animated {// 取消遠程控制[self resignFirstResponder];[[UIApplication sharedApplication] endReceivingRemoteControlEvents]; } 復制代碼接收方法設置
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {if (event.type == UIEventTypeRemoteControl) { //判斷是否為遠程控制switch (event.subtype) {case UIEventSubtypeRemoteControlPlay:if (![_player isPlaying]) {[_player play];}break;case UIEventSubtypeRemoteControlPause:if ([_player isPlaying]) {[_player pause];}break;case UIEventSubtypeRemoteControlNextTrack:NSLog(@"下一首");break;case UIEventSubtypeRemoteControlPreviousTrack:NSLog(@"上一首 ");break;default:break;}} } 復制代碼效果圖:
這樣,播放器的基本功能就已經完成 !! 代碼多有不祥之處,時間匆忙,敬請諒解,不實之處,請多包涵!!
Demo地址: 點此下載
總結
以上是生活随笔為你收集整理的iOS开发 AVAudioPlayer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kickstart 安装CentOS G
- 下一篇: java 分布式电子商务云平台b2b b