繁体   English   中英

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

[英]Prevent muting of background audio when using AVPlayer

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

如果任何后台应用程序正在播放音乐,则只要我在AVPlayer上调用play ,音乐就会静音。 如何防止背景音频静音?

以下是我创建和启动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类中执行以下操作来解决此问题:

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播放另一首歌,它会中断我的后台播放,这就是我想要的行为。

不幸的是,Ron Allan回答并不适合我,但它指出了我正确的方向。 我需要使用的是AVAudioSessionCategoryAmbient类别。

这对我有用(在AppDelegate.swift中):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Don't mute the audio playback
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    } catch {}
    return true
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM