WKWebView兼容问题二:播放音效没声音

亡梦爱人 提交于 2020-03-09 14:19:32

问题描述:

CocosCreator打包web-mobile,在WKWebView框架下运行,播放音效没声音。

解决方案:

在ViewController加入以下代码:

configuration.allowsInlineMediaPlayback = YES;

configuration.mediaPlaybackRequiresUserAction = false;

#import "ViewController.h"
#import <WebKit/WebKit.h>
#define KMainWidth ([UIScreen mainScreen].bounds.size.width)
#define KMainHeight ([UIScreen mainScreen].bounds.size.height)

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

@property(nonatomic,strong)WKWebView *mainWebView;
@property(nonatomic,strong)UIButton *alertButton;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.mainWebView];
    [self.view addSubview:self.alertButton];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (WKWebView *)mainWebView{
    if (_mainWebView == nil) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *userController = [[WKUserContentController alloc] init];
        configuration.userContentController = userController;
        configuration.allowsInlineMediaPlayback = YES;
        configuration.mediaPlaybackRequiresUserAction = false;
        [configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
        _mainWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KMainWidth, KMainHeight) configuration:configuration];
        NSString *path = [[[NSBundle mainBundle] bundlePath]  stringByAppendingPathComponent:@"index.html"];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
        [_mainWebView loadRequest: request];
        _mainWebView.navigationDelegate = self;
        _mainWebView.UIDelegate = self;
        [userController addScriptMessageHandler:self name:@"currentCookies"];
    }
    return _mainWebView;
}

@end

 

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