WKWebView音视频媒体播放处理

1. 对WKWebViewConfiguration进行设置。

实现媒体文件可以自动播放、使用内嵌HTML5播放等功能
使用这个测试网址

// 初始化配置对象
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
// 默认是NO,这个值决定了用内嵌HTML5播放视频还是用本地的全屏控制
configuration.allowsInlineMediaPlayback = YES;
// 自动播放, 不需要用户采取任何手势开启播放
// WKAudiovisualMediaTypeNone 音视频的播放不需要用户手势触发, 即为自动播放
configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
configuration.allowsAirPlayForMediaPlayback = YES;
configuration.allowsPictureInPictureMediaPlayback = YES;

self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
self.webView.navigationDelegate = self;
NSURL *url =[NSURL URLWithString:@"测试网址"];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
[self.view addSubview:self.webView];

由于H5的video未设置autoplay、playsinline属性。我们需自己注入,才能实现效果。

NSString *jSString = @"document.getElementsByTagName('video')[0].setAttribute('playsinline','');";
NSString *jSString2 = @"document.getElementsByTagName('video')[0].autoplay=true;";
//用于进行JavaScript注入
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserScript *wkUScript2 = [[WKUserScript alloc] initWithSource:jSString2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[configuration.userContentController addUserScript:wkUScript];
[configuration.userContentController addUserScript:wkUScript2];


2. 监听网页内播放器的回调

可以使用两种办法。

2.1 利用HTML5 Audio/Video 事件

HTML5 Audio/Video 事件代码可以由H5同事完成,也可以由App端注入。
注入代码如下:


NSString *jSString3 = @"document.getElementsByTagName('video')[0].addEventListener('canplay', function(e) {window.webkit.messageHandlers.readytoplay.postMessage(\"canplay\");})";
NSString *jSString4 = @"document.getElementsByTagName('video')[0].addEventListener('pause', function(e) {window.webkit.messageHandlers.pause.postMessage(\"pause\");})";
NSString *jSString5 = @"document.getElementsByTagName('video')[0].addEventListener('play', function(e) {window.webkit.messageHandlers.play.postMessage(\"play\");})";
NSString *jSString6 = @"document.getElementsByTagName('video')[0].addEventListener('ended', function(e) {window.webkit.messageHandlers.ended.postMessage(\"ended\");})";
WKUserScript *wkUScript3 = [[WKUserScript alloc] initWithSource:jSString3 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[configuration.userContentController addUserScript:wkUScript3];
WKUserScript *wkUScript4 = [[WKUserScript alloc] initWithSource:jSString4 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[configuration.userContentController addUserScript:wkUScript4];
WKUserScript *wkUScript5 = [[WKUserScript alloc] initWithSource:jSString5 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[configuration.userContentController addUserScript:wkUScript5];
WKUserScript *wkUScript6 = [[WKUserScript alloc] initWithSource:jSString6 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[configuration.userContentController addUserScript:wkUScript6];
App端接收js的代码如下:
需遵守WKScriptMessageHandler协议

@interface ViewController () <WKNavigationDelegate,WKScriptMessageHandler>
@end

再为WKWebViewConfiguration添加协议

//添加一个协议
[configuration.userContentController addScriptMessageHandler:self name:@"readytoplay"];
[configuration.userContentController addScriptMessageHandler:self name:@"play"];
[configuration.userContentController addScriptMessageHandler:self name:@"pause"];
[configuration.userContentController addScriptMessageHandler:self name:@"ended"];

使用以下方法即可获取播放器事件

#pragma mark - WKScriptMessageHandler

//! WKWebView收到ScriptMessage时回调此方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name caseInsensitiveCompare:@"readytoplay"] == NSOrderedSame) {
NSLog(@"video is readytoplay");
}
if ([message.name caseInsensitiveCompare:@"play"] == NSOrderedSame) {
NSLog(@"video is play");
}
if ([message.name caseInsensitiveCompare:@"pause"] == NSOrderedSame) {
NSLog(@"video is pause");
}
if ([message.name caseInsensitiveCompare:@"ended"] == NSOrderedSame) {
NSLog(@"video is ended");
}
}
2.2 还有一种是App可自己实现的,使用AVAudioSession进行监听:

使用AVAudioSession监听,必须用到AVAudioSessionCategoryOptionMixWithOthers。这样会导致切换别的音视频App不会打断播放器。例如网易云音乐、bilibili。
手机来电会打断播放器。


NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
withOptions:AVAudioSessionCategoryOptionMixWithOthers
error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionSilenceSecondaryAudioHint:)
name:AVAudioSessionSilenceSecondaryAudioHintNotification
object:[AVAudioSession sharedInstance]];
- (void)audioSessionSilenceSecondaryAudioHint:(NSNotification *)notification
{
NSDictionary *userInfo = notification.userInfo;
NSLog(@"audioSessionSilenceSecondaryAudioHint %@",userInfo);
}

开始播放输出:

2021-04-01 15:22:31.302248+0800 webViewPlayMedia[18078:2811391] audioSessionSilenceSecondaryAudioHint  {
AVAudioSessionSilenceSecondaryAudioHintTypeKey = 1;

结束播放输出:

2021-04-01 15:22:31.382646+0800 webViewPlayMedia[18078:2811391] audioSessionSilenceSecondaryAudioHint  {
AVAudioSessionSilenceSecondaryAudioHintTypeKey = 0;

3. 获取视频播放地址,使用自定义播放器进行播放

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
NSLog(@"WKPhoneWebView didFinishNavigation");

NSString *JsStr = @"(document.getElementsByTagName(\"video\")[0]).src";
[self.webView evaluateJavaScript:JsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
if(![response isEqual:[NSNull null]] && response != nil){
//截获到视频地址了
NSLog(@"response == %@",response);
}else{
//没有视频链接
}
}];
}

4. 坑

4.1 播放视频,会有ERROR提示:
2021-04-01 09:34:57.361477+0800 webViewPlayMedia[17109:2655981] [assertion] Error acquiring assertion: <Error Domain=RBSAssertionErrorDomain Code=3 "Required client entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"MediaPlayback" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Required client entitlement is missing}>
2021-04-01 09:34:57.361610+0800 webViewPlayMedia[17109:2655981] [ProcessSuspension] 0x1043dc990 - ProcessAssertion: Failed to acquire RBS MediaPlayback assertion 'WebKit Media Playback' for process with PID 17110, error: Error Domain=RBSAssertionErrorDomain Code=3 "Required client entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"MediaPlayback" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Required client entitlement is missing}


但是设置了background属性了,依然无法解除,但是不影响播放。
这个问题在https://stackoverflow.com/questions/66493177/required-client-entitlement-is-missing-in-wkwebview亦有提出,但是没有解决方案。

4.2 iOS13.2 13.3系统手机会在加载WKWebView时会连续报错:
2021-04-01 15:55:11.083253+0800 webViewPlayMedia[342:59346] [Process] kill() returned unexpected error 1

在该系统版本下,WKWebView使用配置WKWebViewConfiguration,会无法播放。

资料:收到控制台警告:当我在iOS13.2中加载WKWebView时,[Process] kill() returned unexpected error 1
该错误已在13.4版本中修复。



作者:左方
链接:https://www.jianshu.com/p/a77a33063755


0 个评论

要回复文章请先登录注册