我正在Android n上测试我的应用程序,并试图将YouTube页面加载到我的WebView中并自动播放它们。这是我的onCreate
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TestWebViewClient());
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
mWebView.loadUrl("https://www.youtube.com/watch?v=hzz_6dmv03I?autoplay=1");
//mWebView.loadUrl("https://vimeo.com/117116735");
}
加载页面时,以上不会自动播放YouTube或Vimeo视频。我还尝试将以下内容添加到我的TestWebViewClient
public class TestWebViewClient extends WebViewClient {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
}
}
这实际上成功地自动播放了Vimeo视频链接,但是当我在YouTube视频链接上使用它时,我会收到以下错误:
Uncaught TypeError: Cannot read property 'play' of undefined
对于YouTube视频,我还尝试在查找班级名称后单击"播放"按钮,但这也无效:
public class TestWebViewClient extends WebViewClient {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:(function() {
document.getElementsByClassName('ytp-play-button')[0].click();
})");
}
}
请让我知道是否有一个解决方案,而不涉及使用YouTube数据API。
我能够使用iframe_api为此找到解决方法。我现在正在使用它(code
是视频ID,例如" HZZ_6DMV03I"):
void loadYTVideoInWebView(String code) {
String frameVideo = "<html><body style='margin:0px;padding:0px;'>n" +
" <script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>n" +
" var player;n" +
" function onYouTubeIframeAPIReady()n" +
" {player=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}n" +
" function onPlayerReady(event){player.playVideo();}n" +
" </script>n" +
" <iframe id='playerId' type='text/html' width='400' height='360'n" +
" src='https://www.youtube.com/embed/"+code+"?enablejsapi=1&autoplay=1' frameborder='0'>n" +
" </body></html>";
mWebView.loadDataWithBaseURL("http://www.youtube.com", frameVideo, "text/html", "utf-8", null);
testwebviewclient的更改不需要,但有必要设置:
mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);