
+ (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
// 1. 設定並啟用音訊會話類別
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
// 2. 允許 App 接收遠端控制事件(鎖屏時的播放控制)
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// 3. 建立背景任務 ID,並結束前一個任務
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
if (newTaskId != UIBackgroundTaskInvalid && backTaskId != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:backTaskId];
}
return newTaskId;
}
AVAudioSession *session = [AVAudioSession sharedInstance]; [session setActive:YES error:nil]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; // 讓 App 支援接收遠端控制事件 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// 背景播放任務 ID UIBackgroundTaskIdentifier _bgTaskId; // 設定音訊會話,允許背景播放 _bgTaskId = [SoundTool backgroundPlayerID:_bgTaskId];
補充一點實務經驗:除了程式碼設定,還必須在專案的 Background Modes 中勾選 Audio, AirPlay and Picture in Picture,否則 App 進入背景後音樂仍會被系統停掉。