Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting AVAudioSession Category has no effect on sound from WKWebView

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];

I've also tried activating the sharedInstance like this, but it did not help:

[session setActive: YES error: nil];

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

like image 732
Lyle Pratt Avatar asked Nov 26 '14 14:11

Lyle Pratt


1 Answers

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...

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.

like image 145
Piet Avatar answered Nov 11 '22 03:11

Piet