萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 後台播放音樂並防止鎖屏休眠完整實現

實現「鎖屏/Home 鍵退出後繼續播放音樂」需要配置 **Background Modes**、**Audio Session**、**Idle Timer** 三大核心點。本文提供生產級完整代碼。

1. Info.plist 配置 Background Modes

在 Xcode 專案 Target → Signing & Capabilities → **+ Capability** → **Background Modes** → 勾選 Audio, AirPlay, and Picture in Picture。

對應生成的 Info.plist 片段:

UIBackgroundModes

    audio

2. 導入框架與頭文件

@import AVFoundation;
@import AudioToolbox;
// 或
#import 
#import 

3. 禁止自動鎖屏(可選,視業務而定)

// 只有前台播放視頻、導航等強需求場景才開啟
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
// 記得在不需要時恢復 NO,否則耗電投訴率極高

4. 配置 Audio Session(核心)

- (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;
}

5. 創建並播放 AVAudioPlayer

- (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];
}

6. 處理音頻中斷(來電、鬧鐘、其他 App 搶佔)

- (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];
        }
    }
}

7. 遠程控制事件響應(鎖屏/控制中心/耳機)

- (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;
        }
    }
}

8. 現代替代:AVPlayer / AVAudioEngine

  • AVPlayer:支持流媒體、HLS、資源管理更強大、自動處理中斷恢復。
  • AVAudioEngine:節點圖架構,支持實時效果、混音、空間音頻。
  • MPRemoteCommandCenter:iOS 7.1+ 統一處理遠程控制,替代 remoteControlReceivedWithEvent:。

避坑檢查清單

  • ✅ Info.plist `UIBackgroundModes` 包含 `audio`。
  • ✅ `AVAudioSession` Category 設置為 `Playback` 或 `PlayAndRecord` + `DefaultToSpeaker`。
  • ✅ `setActive:YES` 在播放前調用,並在 `applicationWillResignActive` 時不主動 deactivate。
  • ✅ `AVAudioPlayer` / `AVPlayer` 持有強引用(屬性 `strong`)。
  • ✅ 註冊遠程控制事件並實現響應。
  • ✅ 處理中斷通知,自動恢復播放。
  • ⚠️ `idleTimerDisabled` 僅在**極必要**時開啟,並及時關閉。

配置正確,你的音樂就能在鎖屏、後台、控制中心優雅地持續播放。

copyright © 萬盛學電腦網 all rights reserved