實現「鎖屏/Home 鍵退出後繼續播放音樂」需要配置 **Background Modes**、**Audio Session**、**Idle Timer** 三大核心點。本文提供生產級完整代碼。
在 Xcode 專案 Target → Signing & Capabilities → **+ Capability** → **Background Modes** → 勾選 Audio, AirPlay, and Picture in Picture。
對應生成的 Info.plist 片段:
UIBackgroundModes
audio
@import AVFoundation;
@import AudioToolbox;
// 或
#import
#import
// 只有前台播放視頻、導航等強需求場景才開啟
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
// 記得在不需要時恢復 NO,否則耗電投訴率極高
- (BOOL)configureAudioSession {
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error = nil;
// 類別:播放並錄製(支持後台播放 + 麥克風輸入)
// 純播放可用 AVAudioSessionCategoryPlayback
BOOL success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
error:&error];
if (!success) {
NSLog(@"AudioSession Category 設置失敗: %@", error);
return NO;
}
// 激活會話
success = [session setActive:YES error:&error];
if (!success) {
NSLog(@"AudioSession 激活失敗: %@", error);
return NO;
}
// 可選:設置首選采樣率、IO 緩衝幀數
[session setPreferredSampleRate:44100 error:nil];
[session setPreferredIOBufferDuration:0.005 error:nil]; // 5ms 低延遲
return YES;
}
- (void)startBackgroundPlayback {
[self configureAudioSession];
NSString *path = [[NSBundle mainBundle] pathForResource:@"background_music" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (error) {
NSLog(@"播放器創建失敗: %@", error);
return;
}
self.audioPlayer.numberOfLoops = -1; // -1 = 無限循環
self.audioPlayer.volume = 1.0;
self.audioPlayer.delegate = self; // 處理中斷、解碼錯誤
[self.audioPlayer prepareToPlay]; // 預加載緩衝
[self.audioPlayer play];
// 可選:啟用遠程控制事件(鎖屏/控制中心/耳機線控)
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
// iOS 8+ 棄用,改用 AVAudioSessionInterruptionNotification
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags {
if (flags & AVAudioSessionInterruptionOptionShouldResume) {
[player play];
}
}
// 現代方式:監聽通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleInterruption:)
name:AVAudioSessionInterruptionNotification
object:[AVAudioSession sharedInstance]];
- (void)handleInterruption:(NSNotification *)notification {
NSInteger type = [notification.userInfo[AVAudioSessionInterruptionTypeKey] integerValue];
if (type == AVAudioSessionInterruptionTypeBegan) {
// 被中斷:暫停播放、釋放資源
} else if (type == AVAudioSessionInterruptionTypeEnded) {
NSInteger options = [notification.userInfo[AVAudioSessionInterruptionOptionKey] integerValue];
if (options & AVAudioSessionInterruptionOptionShouldResume) {
[self.audioPlayer play];
}
}
}
- (BOOL)canBecomeFirstResponder { return YES; }
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
if (event.type == UIEventTypeRemoteControl) {
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay: [self.audioPlayer play]; break;
case UIEventSubtypeRemoteControlPause: [self.audioPlayer pause]; break;
case UIEventSubtypeRemoteControlTogglePlayPause:
self.audioPlayer.isPlaying ? [self.audioPlayer pause] : [self.audioPlayer play]; break;
case UIEventSubtypeRemoteControlNextTrack: /* 下一曲 */ break;
case UIEventSubtypeRemoteControlPreviousTrack: /* 上一曲 */ break;
default: break;
}
}
}
AVPlayer:支持流媒體、HLS、資源管理更強大、自動處理中斷恢復。AVAudioEngine:節點圖架構,支持實時效果、混音、空間音頻。MPRemoteCommandCenter:iOS 7.1+ 統一處理遠程控制,替代 remoteControlReceivedWithEvent:。配置正確,你的音樂就能在鎖屏、後台、控制中心優雅地持續播放。