iOS - 使用 AVAudioSessionCategoryAmbient 和 duckOthers 和 mixWithOthers 开启静音

标签 ios audio swift3 avfoundation

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

在我的应用程序中,我播放了一个简短的音频片段,如下所示:

//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)

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

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

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

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

最佳答案

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 一起使用。我建议在您的应用程序委托(delegate)中设置它 didFinishLaunchingWithOptions:

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

关于iOS - 使用 AVAudioSessionCategoryAmbient 和 duckOthers 和 mixWithOthers 开启静音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48230245/

相关文章:

ios - 如何暂停 UIView 动画

ios - 删除 CloudKit 记录 Swift 4

java - OpenJDK 更改 Clp 音量

ios - Swift 3 添加新联系人电话和电子邮件信息

ios - Swift 为现有用户默认值增加值(value)

ios - 在核心数据项目中导入数据和修改实体

ios - 如何使 SKScene 具有固定宽度?

python - 使用 Python PyAudio 播放 2 声道声音

objective-c - .mp3和.wav文件可在模拟器上使用,但不能在设备上使用

sprite-kit - 以变​​化的度数旋转 SKSpritenode