简体   繁体   中英

Prevent muting of background audio when using 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.

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?

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

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
}

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

Ron Allan answer unfortunately didn't work for me, however it pointed me in the right direction. What I needed to use was the AVAudioSessionCategoryAmbient category.

This is what worked for me (in 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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