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());

`

Anuj Garg
  • 167
  • 1
  • 3
  • 14
  • try this url `https://www.youtube.com/embed/oY2OxMpCUVY?autoplay=1` add www to url. – TechArcSri Jan 20 '15 at 06:48
  • my video is working but not able to autoplay.i tried what you said.. not working.. – Anuj Garg Jan 20 '15 at 06:52
  • See https://stackoverflow.com/questions/24947758/how-to-auto-play-iframe-youtube-on-webview-android/76181022#76181022 This is my answer about it. I play with it well. – Daniel May 06 '23 at 01:28

7 Answers7

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());
Dhunju_likes_to_Learn
  • 1,201
  • 1
  • 16
  • 25
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>
Gautam Kushwaha
  • 281
  • 3
  • 15
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());
Orsi
  • 21
  • 4
1

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+)

eladc
  • 243
  • 2
  • 6
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.

David Haim
  • 25,446
  • 3
  • 44
  • 78
0

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

Community
  • 1
  • 1
bonnyz
  • 13,458
  • 5
  • 46
  • 70
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();
}
Shashi Shiva L
  • 495
  • 11
  • 27