简体   繁体   中英

AVAudioSession option change does not take effect

My iOS app plays audio from a URL. Most of the time, I want this audio to not mix with other audio played on the device.

But sometimes, I do want to allow the audio to mix with other audio on the device.

When I initially start my audio, it works as desired; it does not mix with other audio on the device (ie playing music on Spotify will stop my audio from playing). Here's what I call in that case:

try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)

Then when I call the following code, it successfully allows my audio to mix with others as desired:

try! AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)

However, when I try to change it back to not mix with others it does not work; other audio from the device is playing along with my audio. I am calling this again just as I did initially:

try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)

Any idea why I cannot change the AVAudioSession back to not mixing with others?

I appear to have fixed this by calling the following for audio I do not want mixed / playable with other device audio playback:

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(error)
    }

And calling this for audio I do want mixed:

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(error)
    }

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