使用AVPlayer时防止背景音频静音

Cba*_*bas 5 audio objective-c avfoundation ios avplayer

我正在使用AVPlayer实例播放视频,我希望能够在播放视频时继续收听背景音乐.

如果任何后台应用正在播放音乐,则每当我呼叫playAVPlayer 时音乐都会静音.如何防止背景音频静音?

以下是我创建和启动AVPlayer的方法:

AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];

playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
[self.layer addSublayer:playerLayer];

// mutes all background audio
[player play];
Run Code Online (Sandbox Code Playgroud)

小智 2

我能够通过在 AppDelegate.swift 类中执行以下操作来解决此问题:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient)
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    } catch {

    }
    return true
}
Run Code Online (Sandbox Code Playgroud)

我还验证了如果我开始通过 iTunes 播放另一首歌曲,它会中断我的后台播放,这正是我想要的行为。