要播放 App 內建的或已下載到本地的音訊檔,AVAudioPlayer 是最合適的選擇。它支援音量、播放速率、聲道平衡、循環次數與音量計量等完整控制。本文示範基本播放,並說明如何做到鎖屏與切換 App 後仍持續播放。
// 建立音樂檔案路徑
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"eyeExe" ofType:@"mp3"];
// 先確認檔案存在
if ([[NSFileManager defaultManager] fileExistsAtPath:musicFilePath]) {
NSURL *musicURL = [NSURL fileURLWithPath:musicFilePath];
NSError *myError = nil;
// 建立播放器
myBackMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:&myError];
if (myBackMusic == nil) {
NSLog(@"error === %@", [myError description]);
}
[myBackMusic setVolume:1]; // 音量 0.0 ~ 1.0
myBackMusic.numberOfLoops = -1; // -1 代表無限循環
[myBackMusic prepareToPlay]; // 預先準備,可減少首次播放的延遲
}
// 設定鎖屏後仍能繼續播放
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
幾個重點:
pathForResource: 會回傳 nil,後續才崩潰會很難查。/* 以下方法回傳 BOOL:成功為 YES,失敗為 NO */ - (BOOL)prepareToPlay; /* 準備播放,play 時會自動呼叫 */ - (BOOL)play; /* 非同步播放 */ - (BOOL)playAtTime:(NSTimeInterval)time; /* 在未來的某個時刻播放,time 為/deviceCurrentTime 基準的絕對時間 */ - (void)pause; /* 暫停,仍保有就緒狀態 */ - (void)stop; /* 停止,不再處於就緒狀態 */
pause 與 stop 的差別很重要:pause 之後 play 會從暫停處續播;stop 之後則會從頭開始。
/* 狀態 */
@property(readonly, getter=isPlaying) BOOL playing; /* 是否正在播放 */
@property(readonly) NSUInteger numberOfChannels; /* 聲道數 */
@property(readonly) NSTimeInterval duration; /* 音檔總長度(秒) */
/* 委派:實作 AVAudioPlayerDelegate 以接收播放完成通知 */
@property(assign) id delegate;
/* 資料來源(依初始化方式,兩者其一非 nil) */
@property(readonly) NSURL *url; /* 以 URL 初始化時有值 */
@property(readonly) NSData *data; /* 以 NSData 初始化時有值 */
/* 播放控制 */
@property float pan; /* 聲道平衡:-1.0 全左,0.0 置中,1.0 全右 */
@property float volume; /* 音量,標称範圍 0.0 ~ 1.0 */
@property BOOL enableRate; /* 必須設為 YES,rate 才會生效;且要在 prepareToPlay 之前設定 */
@property float rate; /* 播放速率:1.0 正常,0.5 半速,2.0 雙倍速 */
@property NSTimeInterval currentTime; /* 目前播放位置(秒) */
@property(readonly) NSTimeInterval deviceCurrentTime; /* 輸出裝置的目前時間 */
@property NSInteger numberOfLoops;
/* 到達結尾後回到開頭的次數。0 = 只播一次,1 = 播兩次,
負數 = 無限循環直到手動停止 */
@property(readonly) NSDictionary *settings; /* 回傳音訊設定字典 */
/* 音量計量(metering) */
@property(getter=isMeteringEnabled) BOOL meteringEnabled; /* 預設關閉 */
- (void)updateMeters; /* 更新計量值 */
- (float)peakPowerForChannel:(NSUInteger)channelNumber; /* 該聲道的峰值(分貝) */
- (float)averagePowerForChannel:(NSUInteger)channelNumber; /* 該聲道的平均值(分貝) */
enableRate 這組設計很容易踩到:忘記設 YES 就調 rate,症狀是「設了卻沒效果」,而且不會有任何錯誤訊息。
步驟一:在 Info.plist 中加入 Required background modes,新增一項並設值為 App plays audio or streams audio/video using AirPlay。

步驟二:設定 AVAudioSession 的 category:
// 鎖屏後仍繼續播放 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive:YES error:nil];
設為 AVAudioSessionCategoryPlayback 的意義是:無視靜音模式與鎖屏,持續播放音樂;同時不會與其他 App 的聲音混合(會中斷其他 App 的播放)。若想與其他 App 並存,可額外設定 kAudioSessionProperty_OverrideCategoryMixWithOthers。
NSString *const AVAudioSessionCategoryAmbient; /* 環境音 */ NSString *const AVAudioSessionCategorySoloAmbient; /* 獨占環境音(預設) */ NSString *const AVAudioSessionCategoryPlayback; /* 播放 */ NSString *const AVAudioSessionCategoryRecord; /* 錄音 */ NSString *const AVAudioSessionCategoryPlayAndRecord; /* 播放 + 錄音 */ NSString *const AVAudioSessionCategoryAudioProcessing; /* 音訊處理 */
實際行為對照:
MPRemoteCommandCenter(iOS 7.1 之後為 MPNowPlayingInfoCenter 搭配 MPRemoteCommandCenter)。AVAudioSessionInterruptionNotification,必須在通知中暫停播放,並於 AVAudioSessionInterruptionOptionShouldResume 時恢復。AVAudioSessionCategoryPlayback 等「字串常數」寫法在 iOS 10 之後已改為 AVAudioSession.Category.playback(Swift)或 AVAudioSessionCategoryPlayback 仍可用但建議改用新的 setCategory:error: 語意。新專案請參考最新文件。整體流程就是:建立 AVAudioPlayer → 設定 category 為 Playback → 在 plist 宣告 background audio → 實作遠端控制與中斷處理。四步完成,就能做出一個鎖屏也不中斷的播放器。