android webview youtube embed video autoplay not working
Asked Answered
P

7

8

i am not able to autoplay my video please help in this. my sdk version

  android:minSdkVersion="14"
    android:targetSdkVersion="19" />

i tried to put java script as specifed in code:

 public void onPageFinished(WebView view, String url) { webView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
            });

i also try to append autoplay in URL but not working //webView.loadUrl("http://youtube.com/embed/oY2OxMpCUVY?autoplay=1");

my web settings `

customViewContainer = (FrameLayout)rootView.findViewById(R.id.customViewContainer);
        webView = (WebView) rootView.findViewById(R.id.HelpView_Video);
        final GlobleClass globalVariable = (GlobleClass) GlobleClass.getContext();
        mWebViewClient = new HelpWebViewClient();
        webView.setWebViewClient(mWebViewClient);
        mWebChromeClient = new myWebChromeClient();
        webView.setWebChromeClient(mWebChromeClient);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(PluginState.ON);
        webView.setWebViewClient(new WebViewClient() {
            // autoplay when finished loading via javascript injection
            public void onPageFinished(WebView view, String url) { webView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
        });
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
//        }
        webView.getSettings().setAppCacheEnabled(true);
        //webView.getSettings().setBuiltInZoomControls(true);
      //  webView.getSettings().setSaveFormData(true);
        //webView.loadUrl("http://youtube.com/embed/oY2OxMpCUVY?autoplay=1");
        webView.loadUrl(globalVariable.getHelpVideoUrl());

`

Placencia answered 20/1, 2015 at 6:42 Comment(3)
try this url https://www.youtube.com/embed/oY2OxMpCUVY?autoplay=1 add www to url.Shackelford
my video is working but not able to autoplay.i tried what you said.. not working..Placencia
See #24948258 This is my answer about it. I play with it well.Dialecticism
A
10

Inspired by Orsi's answer, I was able to mimic onClick() event on the center of the WebView that showed video player. This ultimately played the video automatically, or rather, without user's interaction.

private class AutoPlayVideoWebViewClient extends WebViewClient {

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        // mimic onClick() event on the center of the WebView
        long delta = 100;
        long downTime = SystemClock.uptimeMillis();
        float x = view.getLeft() + (view.getWidth()/2);
        float y = view.getTop() + (view.getHeight()/2);

        MotionEvent tapDownEvent = MotionEvent.obtain(downTime, downTime + delta, MotionEvent.ACTION_DOWN, x, y, 0);
        tapDownEvent.setSource(InputDevice.SOURCE_CLASS_POINTER);
        MotionEvent tapUpEvent = MotionEvent.obtain(downTime, downTime + delta + 2, MotionEvent.ACTION_UP, x, y, 0);
        tapUpEvent.setSource(InputDevice.SOURCE_CLASS_POINTER);

        view.dispatchTouchEvent(tapDownEvent);
        view.dispatchTouchEvent(tapUpEvent);
    }
}

Somewhere,

myWebView.setWebViewClient(new AutoPlayVideoWebViewClient());
Aesthete answered 13/8, 2017 at 0:4 Comment(0)
D
4

First used below code :

webSettings.setMediaPlaybackRequiresUserGesture(false);

After that used below method for loading:

webView.loadDataWithBaseURL("https://www.youtube.com/", HTML.replace("CUSTOM_ID","YOUR_YOUTUBE_VIDEO_ID"), "text/html", "utf-8", null);

In HTML string pass below Code with YouTube API (Replaced your YouTube video ID)

    <!DOCTYPE html>
<html>
 <style type="text/css">
        html, body {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
            background-color: #000000;
            overflow: hidden;
            position: fixed;
        }
    </style>
<body>

 <div id="player"></div>
<script>
       var tag = document.createElement('script');
       tag.src = "https://www.youtube.com/player_api";
       var firstScriptTag = document.getElementsByTagName('script')[0];
       firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
       var player;
       function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
                    height: '100%',
                    width: '100%',
                    videoId: 'CUSTOM_ID',
                    events: {
                       'onReady': onPlayerReady,
                       'onStateChange': onPlayerStateChange
                  },
                  playerVars: {
                        'autoplay': 0,
                        'showinfo': 1,
                        'controls': 1
                                }
                            });
                        }
                        function onPlayerReady(event) {
                            event.target.playVideo();

                        }

                        var done = false;
                        function onPlayerStateChange(event) {
                            if (event.data == YT.PlayerState.PLAYING && !done) {
                                done = true;
                            }
                        }
                        function stopVideo() {
                            player.stopVideo();
                        }
                    </script> 

</body>
</html>
Demakis answered 9/7, 2018 at 5:50 Comment(1)
thx. It really works to me. The 'playerVars' seems to be unnecessary.Yacketyyak
C
2

Finally I made it.. You need to use this API to play the video on "OnReady" event: https://developers.google.com/youtube/iframe_api_reference#Getting_Started

Load the page that contains the code from this example.

And make sure you have

webSettings.setMediaPlaybackRequiresUserGesture(false);

(API 16+)

Celebrated answered 19/5, 2016 at 7:20 Comment(1)
Cool. So Google provided a guide-preference. Never know that.Yacketyyak
M
2

The C# version of the code posted by bonnyz in his answer here. Just in case someone needs it for Xamarin :) I tested it and it works. It was the only solution I have found to autoplay youtube videos in a webview.

public class MyWebViewClient : WebViewClient
{
    WebView webView;
    MotionEvent motionEvent, motionEvent2;

    public override void OnPageFinished(WebView view, string url)
    {
        long delta = 100;
        long downTime = SystemClock.UptimeMillis();
        float x = view.Left + view.Width / 2;
        float y = view.Top + view.Height / 2;
        webView = view;

        motionEvent = MotionEvent.Obtain(downTime, downTime + delta, MotionEventActions.Down, x, y, 0);
        motionEvent2 = MotionEvent.Obtain(downTime + delta + 1, downTime + delta * 2, MotionEventActions.Up, x, y, 0);

        int delay = 100;
        view.PostDelayed(TapDown, delay);
        delay += 100;
        view.PostDelayed(TapUp, delay);
    }


    private void TapDown()
    {
        webView.DispatchTouchEvent(motionEvent);
    }

    private void TapUp()
    {
        webView.DispatchTouchEvent(motionEvent2); 
    }
}

To use it:

webView.SetWebViewClient(new MyWebViewClient());
Metempirics answered 30/5, 2017 at 12:3 Comment(1)
thanks to this answer, I manged to do it in Java with some critical tweaks tho. See, https://mcmap.net/q/1263675/-android-webview-youtube-embed-video-autoplay-not-workingAesthete
G
0

You can't do autoplay with JavaScript on the webview. In order to enhance user experience , WebKit disables the option to autoplay videos on mobile browsers.

Gamber answered 20/1, 2015 at 6:59 Comment(1)
how can i enable that option?Placencia
H
0

The autoplay issue is a known problem, please take a look to my answer here.

Howarth answered 23/1, 2015 at 9:13 Comment(0)
D
0

Adding value @Dhunju_likes_to_Learn's answer. Handling the back button pressed in onResume, onPause and onDestroy methods as suggested by Thiago

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    setContentView(R.layout.your_layout);
    // Call the AutoPlayVideoWebViewClient class in onCreate method
    myWebView.setWebViewClient(new AutoPlayVideoWebViewClient());
}

Write a private

private class AutoPlayVideoWebViewClient extends WebViewClient {

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    // mimic onClick() event on the center of the WebView
    long delta = 100;
    long downTime = SystemClock.uptimeMillis();
    float x = view.getLeft() + (view.getWidth()/2);
    float y = view.getTop() + (view.getHeight()/2);

    MotionEvent tapDownEvent = MotionEvent.obtain(downTime, downTime + delta, MotionEvent.ACTION_DOWN, x, y, 0);
    tapDownEvent.setSource(InputDevice.SOURCE_CLASS_POINTER);
    MotionEvent tapUpEvent = MotionEvent.obtain(downTime, downTime + delta + 2, MotionEvent.ACTION_UP, x, y, 0);
    tapUpEvent.setSource(InputDevice.SOURCE_CLASS_POINTER);

    view.dispatchTouchEvent(tapDownEvent);
    view.dispatchTouchEvent(tapUpEvent);
}
}

@Override
public void onPause() {
    myWebView.onPause();
    myWebView.pauseTimers();
    super.onPause();
}

@Override 
public void onResume() {
    super.onResume();
    myWebView.resumeTimers();
    myWebView.onResume();
}

@Override
protected void onDestroy() {
    myWebView.destroy();
    myWebView = null;
    super.onDestroy();
}
Dripstone answered 26/7, 2021 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.