android webview youtube嵌入视频自动播放无法正常工作

时间:2015-01-20 06:42:30

标签: java android webview youtube youtube-javascript-api

我无法自动播放我的视频,请帮忙。 我的sdk版本

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

我试着把java脚本放在代码中指定:

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

我还尝试在网址中附加自动播放但不能正常工作 //webView.loadUrl("http://youtube.com/embed/oY2OxMpCUVY?autoplay=1");

我的网页设置 `

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

`

7 个答案:

答案 0 :(得分:1)

受到Orsi answer的启发,我能够在显示视频播放器的WebView中心模仿onClick()事件。这最终会在没有用户互动的情况下自动播放视频。

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

某处,

myWebView.setWebViewClient(new AutoPlayVideoWebViewClient());

答案 1 :(得分:1)

首先在下面的代码中使用:

webSettings.setMediaPlaybackRequiresUserGesture(false);

之后,使用以下方法进行加载:

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

在HTML字符串中,在带有YouTube API的代码下方传递(替换为YouTube视频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>

答案 2 :(得分:0)

您无法在网页浏览中使用JavaScript进行自动播放。 为了增强用户体验,WebKit禁用了在移动浏览器上自动播放视频的选项。

答案 3 :(得分:0)

自动播放问题已知问题,请查看我的回答here

答案 4 :(得分:0)

最后我做到了.. 您需要使用此API在“OnReady”事件上播放视频: https://developers.google.com/youtube/iframe_api_reference#Getting_Started

加载包含此示例代码的页面。

确保你有

webSettings.setMediaPlaybackRequiresUserGesture(false);

(API 16 +)

答案 5 :(得分:0)

bonnyz在他的回答here中发布的C#版代码。以防有人需要它为Xamarin :)我测试它,它的工作原理。这是我发现在webview中自动播放YouTube视频的唯一解决方案。

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

使用它:

webView.SetWebViewClient(new MyWebViewClient());

答案 6 :(得分:0)

增加价值@Dhunju_likes_to_Learn 的回答。按照 Thiago

的建议处理在 onResume、onPause 和 onDestroy 方法中按下的后退按钮
@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());
}

写私信

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