WKWebView embed video keeps playing sound after release

心已入冬 提交于 2019-12-19 09:28:01

问题


I'm implementing a service for playing video files with a webview. I migrated from UIWebView to WKWebView, and trying to play Youtube and Coub videos with it. Almost everything is okay, no crashes in iOS 8, but after WKWebView released and removed from screen, video sound keeps playing for a while (in some cases about 45 seconds).

I can't find the way to stop sound of video. I tried to catch system notifications with a media player, but no success.

Is there any way to stop sound or video in WKWebView?

WKWebview configuration is next:

//javascript for configurate video viewport (not full screen)
NSString *jScript = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%d, height=%d, initial-scale=1, maximum-scale=1'); document.getElementsByTagName('head')[0].appendChild(meta);", (int)VIEW_WIDTH, (int)VIEW_HEIGHT ];

WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];

WKWebViewConfiguration *config    = [WKWebViewConfiguration new];
config.mediaPlaybackAllowsAirPlay = YES;
config.userContentController      = wkUController;

_wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT) configuration:config];
[_wkWebView setBackgroundColor:RGB(0x0a0a0a)];
[_wkWebView setNavigationDelegate:self];
[self insertSubview:_wkWebView atIndex:0];

回答1:


You can load blank page [NSURL URLWithString:@"about:blank"]

There is probably better solution though

UPDATE: fixed in iOS 8.3




回答2:


I'd recommend stopping video with JS code. For example

let stopVideoScript = "var videos = document.getElementsByTagName('video'); for( var i = 0; i < videos.length; i++ ){videos.item(i).pause()}"
self.webView.evaluateJavaScript(stopVideoScript, completionHandler:nil)


来源:https://stackoverflow.com/questions/27410413/wkwebview-embed-video-keeps-playing-sound-after-release

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!