使用AVPlayer时防止背景音频静音 [英] Prevent muting of background audio when using AVPlayer

查看:55
本文介绍了使用AVPlayer时防止背景音频静音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am playing a video using an instance of AVPlayer and I want to be able to continue listening to background music while playing the video.

如果有任何后台应用程序正在播放音乐,则每当我在AVPlayer上调用 play 时,音乐就会被静音.如何防止背景音频被静音?

If any background app is playing music, the music is muted whenever I call play on the AVPlayer. How can I prevent background audio from being muted?

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

Here's how I create and start my 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];

推荐答案

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

I was able to solve this problem by doing the following in the AppDelegate.swift class:

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
}

我还验证了,如果我开始通过iTunes播放另一首歌曲,则会中断我的背景播放,这是我想要的行为.

I also verified that if I began playing another song through iTunes it would interrupt my background playback, which is the behaviour I wanted.

这篇关于使用AVPlayer时防止背景音频静音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆