在 iOS 中,音訊播放從形式上可分為音效播放與音樂播放。前者多指短音訊,作為點綴音,通常不需進度、循環等控制;後者則是較長的主音訊,需要精確控制。iOS 分別用 AudioToolbox.framework 與 AVFoundation.framework 來完成音效與音樂播放。
一、音效
AudioToolbox.framework 是一套基於 C 語言的框架,播放音效的本質是將短音訊註冊到系統聲音服務(System Sound Service)。它簡單、底層,適合播放小提示音或警告音,還能觸發震動,但有幾項限制:音訊不能超過 30 秒、資料須為 PCM 或 IMA4 格式、檔案須打包成 .caf/.aif/.wav(實測部分 .mp3 也可播放)、不能控制進度、呼叫後立即播放、沒有循環與立體聲控制。
二、音樂
若要播放較大的音訊或精確控制,System Sound Service 就難以滿足,通常會改用 AVFoundation.framework 中的 AVAudioPlayer。它可看作一個進階播放器,支援廣泛的音訊格式:能播放任意長度、支援循環、可同步播放多個檔案、能控制進度並從任意點開始播放。只要將 numberOfLoops 設為負數,就會一直循環直到呼叫 stop。
AVAudioPlayer 封裝了播放單一聲音的能力,可用 NSURL 或 NSData 初始化,但 NSURL 必須是本地檔案(它不具備播放網路音訊的能力),且因不支援串流,必須緩衝完成才能播放。想混音則可建立多個 AVAudioPlayer 實例,每個如同混音板上的一軌。
進階應用
1. 設定背景播放(兩步缺一不可):第一步在 Required background modes 勾選 App plays audio;第二步將 AVAudioSession 類型設為 AVAudioSessionCategoryPlayback 並呼叫 setActive 啟動:
AVAudioSession *audioSession=[AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil];
2. 處理拔出耳機後暫停:監聽 AVAudioSessionRouteChangeNotification,當改變原因為 AVAudioSessionRouteChangeReasonOldDeviceUnavailable 且原輸出為耳機時,暫停播放。
iOS 9 網路設定
在 Info.plist 中設定 NSAppTransportSecurity 與 NSAllowsArbitraryLoads 以允許 HTTP 存取。
搖一搖 demo
#import "ViewController.h" #import @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{ SystemSoundID soundID; NSURL * url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"shake" ofType:@"wav"]]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID); AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); AudioServicesPlaySystemSound(soundID); } -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{ NSLog(@"搖動結束"); }
音樂播放方法(重點程式碼)
-(void)createAudioPlayer{ NSURL * url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:self.localMusicArray[_currentIndex] ofType:@"mp3"]]; _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; _audioPlayer.delegate = self; _audioPlayer.volume = 0.5; _audioPlayer.numberOfLoops = 0; _audioPlayer.currentTime = 0; [_audioPlayer prepareToPlay]; } -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{ if (flag) { }else{ } }
背景播放與開啟線控(重點程式碼)
-(void)dealWithDetail{ AVAudioSession * session = [[AVAudioSession alloc] init]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; [session setActive:YES error:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil]; }
錄音 demo(重點程式碼)
-(void)createAudioRecoder{ NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/recoder.aac"]; NSDictionary * dic = @{AVFormatIDKey:@(kAudioFormatMPEG4AAC), AVSampleRateKey:@(4000.0), AVNumberOfChannelsKey:@(2) }; _audioRecoder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:path] settings:dic error:nil]; _audioRecoder.delegate = self; [_audioRecoder prepareToRecord]; } -(void)startPlay{ _player = [[AVPlayer alloc] init]; AVPlayerItem * item = [AVPlayerItem playerItemWithURL:_audioRecoder.url]; [_player replaceCurrentItemWithPlayerItem:item]; [_player play]; }
視訊播放
一、MPMoviePlayerController
支援本地與網路視訊播放,實作了 MPMediaPlayback 協議,具備播放、暫停、停止等控制功能。但它本身並非完整的視圖控制器,若要在 UI 中展示,需將 view 屬性加入介面。
二、MPMoviePlayerViewController
由於 MPMoviePlayerController 通常佔滿整個螢幕,蘋果在 iOS 3.2 後提供了 MPMoviePlayerViewController,它內部含一個 MPMoviePlayerController,預設全螢幕播放、彈出後自動播放,點擊 Done 會自動退出模態視窗。
iOS9之前: MPMoviePlayerViewController * player = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:@"https://video.szzhangchu.com/1442391674615_6895658983.mp4"]]; player.moviePlayer.controlStyle = MPMovieControlStyleFullscreen; [player.moviePlayer prepareToPlay]; [player.moviePlayer play]; [self presentViewController:player animated:YES completion:nil]; iOS9之後: AVPlayerViewController * playerVC = [[AVPlayerViewController alloc]init]; AVPlayer * player = [AVPlayer playerWithURL:url]; playerVC.player = player; [self presentViewController:playerVC animated:YES completion:nil];
三、AVPlayer
MPMoviePlayerController 高度封裝,難以自訂;若要自由控制則可用 AVPlayer。它位於 AVFoundation,更貼近底層、靈活性更高。AVPlayer 本身不能顯示視訊,需建立 AVPlayerLayer 來展示,並將其加入控制器視圖的 layer。常用類別有:AVAsset(抽象類,用於取得多媒體資訊)、AVURLAsset(可依 URL 建立)、AVPlayerItem(媒體資源管理物件)。播放與暫停對應 play、pause 方法;由於沒有狀態屬性,通常透過 rate 判斷播放狀態(0 為停止、1 為正常播放)。
無論 MPMoviePlayerController 還是 AVPlayer,支援的編碼格式都有限(H.264、MPEG-4,副檔名 .mp4、.mov、.m4v 等),但都支援絕大多數音訊編碼。
四、VLC 視訊播放(第三方整合)
整合步驟:加入 libMobileVLCKit;加入 libstdc++、libiconv、libbz2、Security、QuartzCore、CoreText、CFNetwork、OpenGLES、AudioToolbox 等庫;將 C++ 編譯器設為 libstdc++;在 Header Search Paths 加入 MobileVLCKit 的路徑;引入 VLCMediaPlayer.h;並將使用到的檔案改為 .mm 以支援 C++。
配置 iOS 9
同樣需在 Info.plist 設定 NSAppTransportSecurity 與 NSAllowsArbitraryLoads。