Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to autoplay YouTube video in a PhoneGap/Cordova app

I'm developing an app using PhoneGap. So, it's a web app. In this app, I have a requirement to embed a YouTube video and autoplay it whenever the user navigates to that particular page.

I've read that HTML5 video autoplay doesn't work on mobile devices because of bandwidth concers. My question is that is there any way at all to bypass this restriction? I don't mind complex workarounds or hacks that could allow me to do this. Anything at all.

Thanks.

like image 509
wiseindy Avatar asked Aug 31 '15 04:08

wiseindy


2 Answers

As you pointed out yourself, all autoplay instructions in your code itself will be ignored on load. So we'll implement a function that gets the video in the body and starts playing it.

The following javascript code could do this:

(function() {
    document.getElementsByTagName('video')[0].play();
})()

To execute this code after the page has loaded, we need to set a WebViewClient and implement onPageFinished()

webview.setWebViewClient(new CordovaWebViewClient(this, webview) {
            // autoplay when finished loading via javascript injection
            public void onPageFinished(WebView view, String url) { webview.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});

final WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setPluginState(WebSettings.PluginState.ON);

A full example:

    webview = new CordovaWebView(this);
    setContentView(webview);

    final WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setPluginState(WebSettings.PluginState.ON);

    webview.setWebViewClient(new CordovaWebViewClient() {
        // autoplay when finished loading via javascript injection
        public void onPageFinished(WebView view, String url) { webview.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
    });

    webview.loadUrl("http://html5demos.com/video");
like image 156
Mdlc Avatar answered Nov 19 '22 01:11

Mdlc


There is a cordova/phonegap plugin that promises to do this. It rely on the Webview method setMediaPlaybackRequiresUserGesture, added in API level 17 (Android 4.2).

It simply call this method on the webview:

WebView view = getWebViewFromPlugin();
view.getSettings().setMediaPlaybackRequiresUserGesture(false);

It's also available in phongap build.

like image 41
lifeisfoo Avatar answered Nov 18 '22 23:11

lifeisfoo