【问题标题】:iOS - silent switch on with AVAudioSessionCategoryAmbient and duckOthers and mixWithOthersiOS - 使用 AVAudioSessionCategoryAmbient 和 duckOthers 和 mixWithOthers 开启静音
【发布时间】:2023-12-22 17:29:01
【问题描述】:

我有一个关于 AVAudioSession 的问题。当我的 sn-p 播放时,我想躲避和混合正在运行的音乐(例如来自 Spotify),但它也应该被 Ring/Silent 开关静音。

在我的应用中,我播放一个短音频 sn-p,如下所示:

//set my cateory first
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with: [.duckOthers])

//... when audio will start playing
AVAudioSession.sharedInstance().setActive(true)
myPlayer.play()

//... when audio snipped has finished
AVAudioSession.sharedInstance().setActive(false)

当响铃/静音开关关闭时,这可以正常工作。音乐被闪避,我的音频被播放。音频结束后,音乐进入前台。

现在,当响铃/静音开关打开时,我的 sn-p 没有播放,但正在运行的音乐被闪避,这不是我想要的行为。

那么,当我当前会话处于活动状态时,是否有任何组合或解决方案可以在开关打开时静音音频并避开其他音频?

我发现了那些关于检测静音开关的存储库(MuteSoundSwitch),但这对我来说看起来很脏。

【问题讨论】:

    标签: ios audio swift3 avfoundation


    【解决方案1】:

    https://apple.stackexchange.com/questions/222775/game-audio-is-tied-to-the-ringer-switch-is-this-a-bug-or-a-feature

    不幸的是,这是针对 AVAudioSessionAmbient 的 Apple 行为。您是在告诉 iPhone,您的应用程序中的所有音频都是不必要的,如果静音开关打开,则可以忽略。

    尝试改用 AVAudioSessionCategoryPlayback: https://developer.apple.com/documentation/avfoundation/avaudiosessioncategoryplayback?language=objc

    它也可以与 .duckOthers 一起使用。我建议在您的应用委托中设置它 didFinishLaunchingWithOptions:

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [.duckOthers])
    

    【讨论】: