问题描述
从WKWebView播放音频时,我似乎无法覆盖AVAudioSession类别或端口。使用普通UIWebView时,相同的代码可以正常工作。
I can not seem to override the AVAudioSession category or port when audio is being played from a WKWebView. The same code works perfectly when using a normal UIWebView.
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];
我也试过激活 sharedInstance
像这样,但它没有帮助:
I've also tried activating the sharedInstance
like this, but it did not help:
[session setActive: YES error: nil];
以上代码对来自WKWebView的音频没有影响。我确实在Twitter上发现一些报告称iOS 8.1正在将WKWebView音频与后台应用音频混合在一起,但我无法找到它的来源。请参阅此twitter帖子以供参考:
The above code has no effect on audio coming from a WKWebView. I did find some reports on Twitter that iOS 8.1 is mixing WKWebView audio with background app audio, but I couldn't find the source for that. See this twitter thread for reference: https://twitter.com/marcoarment/status/530881842900373504
推荐答案
显然,WKWebView在与您的应用程序不同的进程中运行。这可能意味着,它也有自己的AudioSession,与你的应用程序的AudioSession分开。这就是为什么更改应用程序的AudioSession不会影响webView的原因。以及为什么它适用于UIWebView(没有单独的过程)。至少那是我到目前为止收集到的...
So apparently WKWebView runs in a separate process from your app. Which probably means, it has its own AudioSession separate from your app's AudioSession as well. That's why changes to your app's AudioSession won't affect the webView. And also why it works with UIWebView (no separate process). At least that's what I gathered so far...
我的解决方案是允许我的应用程序的AudioSession与其他人混合:
The solution for me was to allow my app's AudioSession to mix with others:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionMixWithOthers
error:&error];
当然这也有其他含义。您应用的音频将与所有其他应用的音频混合,而不仅仅是您的网络视图。
Of course this has other implications as well. Your app's audio will be mixed with all other apps' audio, not just your webview's.
这篇关于设置AVAudioSession类别对WKWebView的声音没有影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!