iOS 提供四種音頻播放途徑:System Sound Services(系統聲音服務)、OpenAL(跨平台開源音頻接口)、Audio Queue Services(音頻播放與錄制服務)、AVAudioPlayer(高級音頻播放器)。實踐中最常用的是前兩者中的 System Sound Services 與 AVAudioPlayer。
這是最底層也最簡單的方案,調用 AudioServicesPlaySystemSound 就能發出聲音,框架為基於 C 語言的 AudioToolbox.framework,本質是把短音頻註冊到系統聲音服務。
適用場景:極短的提示音、警告音。
局限性:音頻長度需小於 30 秒;格式必須是 PCM 或 IMA4;無法控制播放進度;調用後立即播放;不支持循環與立體聲。
#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>
@implementation ViewController
- (IBAction)playAction:(id)sender {
// 取得主資源包
CFBundleRef mainBundle = CFBundleGetMainBundle();
SystemSoundID soundFileObject;
// 取得音頻文件 URL
CFURLRef soundFileURLRef = CFBundleCopyResourceURL(mainBundle,
CFSTR("sound"),
CFSTR("wav"),
NULL);
// 註冊到系統聲音服務
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject);
// 添加播放完成回調,可借此實現循環播放
AudioServicesAddSystemSoundCompletion(soundFileObject, NULL, NULL, &completionCallback, (__bridge void *)self);
// 播放
AudioServicesPlaySystemSound(soundFileObject);
// 如需震動反饋
// AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
static void completionCallback(SystemSoundID ssID, void *clientData) {
NSLog(@"播放完成 - ID 為 %u", (unsigned int)ssID);
AudioServicesPlaySystemSound(ssID); // 回調裡再次播放,即實現循環
}
void playFinished(SystemSoundID ssID, void *clientData) {
NSLog(@"播放完成 - ID 為 %u", (unsigned int)ssID);
AudioServicesPlaySystemSound(ssID);
// 移除完成回調
// AudioServicesRemoveSystemSoundCompletion(ssID);
// 釋放自定義系統聲音
// AudioServicesDisposeSystemSoundID(ssID);
}
@end
高級播放器,支持的格式明顯更廣:AAC、AMR、ALAC(Apple Lossless)、iLBC、IMA4、linearPCM(未壓縮)、MP3。
優勢:支持更多格式;可播放任意長度音頻;支持循環;可同步播放多個音頻;可控制進度並從任意位置開始播放。
1)導入 AVFoundation.framework 並引入頭文件 #import <AVFoundation/AVFoundation.h>。
2)初始化時傳入播放文件:AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:path error:nil];
重要屬性:volume(0.0 ~ 1.0)、numberOfLoops(負數表示無限循環)、currentTime(播放進度)。
重要方法:prepareToPlay(預播放)、play、pause、stop。
AVAudioPlayerDelegate 中的兩個回調:播放完成 audioPlayerDidFinishPlaying:successfully:,解碼失敗 audioPlayerDecodeErrorDidOccur:error:。
視頻播放使用 AVPlayer,同樣位於 AVFoundation 框架。它與 AVAudioPlayer 相似但功能更強,音頻視頻通吃,而且可以直接播放網絡音頻。
1)導入 AVFoundation.framework。
2)取得播放地址。
3)用 URL 創建 AVPlayerItem,它能提供視頻信息、當前時間、總時長等。其 status 有三種狀態:Unknown(出現未知問題)、ReadyToPlay(可播放)、Failed(無法播放);loadedTimeRange 代表已緩存進度,監聽它可以在界面上更新緩存條。
4)用 AVPlayerItem 初始化 AVPlayer。
5)AVPlayer 本身不提供視圖,需要創建 AVPlayerLayer 並添加到頁面的 layer 上。
6)配置 AVPlayerLayer 並開始播放。
7)可指定時間點播放。
8)監聽播放完成通知。
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
/// 播放控件,也可用於播放音頻
@property (nonatomic, strong) AVPlayer *player;
/// 播放總時長
@property (nonatomic, assign) CGFloat sumPlayOperation;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *playString = @"https://example.com/video.mp4";
NSURL *url = [NSURL URLWithString:playString];
// 創建播放項目
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
// 初始化播放器
self.player = [[AVPlayer alloc] initWithPlayerItem:item];
// AVPlayer 沒有視圖,必須掛 AVPlayerLayer
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
layer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300);
layer.backgroundColor = [UIColor cyanColor].CGColor;
layer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.view.layer addSublayer:layer];
self.progressSlider.value = 0;
self.player.volume = 1.0f;
}
#pragma mark - 開始播放
- (IBAction)startPlayer:(id)sender {
[self.player play];
}
#pragma mark - 停止播放
- (IBAction)stopPlayer:(id)sender {
[self.player pause];
}
#pragma mark - 改變播放進度
- (IBAction)changePlaye:(id)sender {
self.sumPlayOperation = self.player.currentItem.duration.value / self.player.currentItem.duration.timescale;
// 參數一為目標時間,參數二為每秒幀數
[self.player seekToTime:CMTimeMakeWithSeconds(self.progressSlider.value * self.sumPlayOperation,
self.player.currentTime.timescale)
completionHandler:^(BOOL finished) {
[self.player play];
}];
}
@end
視頻體積大,下載必須異步。實踐思路:繼承 NSOperation 封裝下載任務;開啟 runloop 保證任務正常結束;使用 iOS 8 提供的 NSURLSessionConfiguration 支持後台下載;注意 AFN 本身並未提供下載場景的線程安全保證,多任務並發時需自行處理。
短提示音用 System Sound Services,幾十行代碼搞定;需要循環、進度控制、多軌混音或播放較長音頻,用 AVAudioPlayer;只要播放網絡流媒體或本地視頻,AVPlayer 是最合適的入口;若需要更細粒度的解碼與自定義渲染,才需要下探到 Audio Queue 或 AVFoundation 的更底層接口。