AVAudioSession setCategory 成功但没有任何反应

AVAudioSession setCategory success but nothing happens

我正在编写一个 iOS 具有核心音频的应用程序。遇到奇怪的事情。

待办事项:

AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *err = nil;
[session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDuckOthers error:&err];
[session setActive:YES error:&err];

我发现一切正常,背景音乐被隐藏了。然后我尝试恢复它:

[session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&err];

没有错误,但背景音乐仍然被忽略。 然后我将其替换为:

[session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:0 error:&err];

有效!背景音乐没有了!

我只是不明白为什么我第一次尝试失败而第二次尝试成功?

在我看来,没有区别!

您每次尝试都设置了不同的选项。 AVAudioSessionCategoryOptionDuckOthersAVAudioSessionCategoryOptionMixWithOthers0 之间有区别。

AVAudioSessionCategoryOptionMixWithOthers :将来自此会话的音频与来自其他活动会话的音频混合。

AVAudioSessionCategoryOptionDuckOthers : 导致其他会话的音频在播放此会话的音频时被回避(降低音量)。

0表示没有选项。

因此,其他选项需要另一个会话来执行任务。

有关会话选项的更多详细信息,请参阅 Apple documentation

希望这会有所帮助:)

首先,这两行代码并不等价。 AVAudioSessionCategoryOptionMixWithOthers 实际上值为 1。设置值 0 表示您不需要任何类别选项。

其次,不清楚您实际想要实现的目标。你说你想隐藏其他音频通道(i.a。让它们以较低的音量播放)然后删除这个效果(这将设置 AVAudioSessionCategoryOptionMixWithOthers 选项)。但是然后你通过背景音乐消失来表明你的成功,这完全是另外一回事。

编辑

要移除回避效果,请尝试停用回避会话,而不是在其上设置新类别。

来自 Apple 文档:

当闪避发生时,设备上的所有其他音频(phone 音频除外)的音量都会降低。使用回避的应用程序必须管理其会话的激活状态。在播放音频之前激活音频会话并在播放音频之后停用会话。