在Android webview中自动播放vimeo视频

时间:2012-01-27 08:11:58

标签: android video-streaming vimeo

我设法使用以下内容获取加载和播放的vimeo视频。但是,vimeo oembed doc中指示的autoplay = 1在加载时不会自动播放。任何人都找到了自动播放的方法(还需要在视频播放时捕捉事件)

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);

// how plugin is enabled change in API 8
if (Build.VERSION.SDK_INT < 8) {
  mWebView.getSettings().setPluginsEnabled(true);
} else {
  mWebView.getSettings().setPluginState(PluginState.ON);
}
mWebView.loadUrl("http://player.vimeo.com/video/24577973?player_id=player&autoplay=1&title=0&byline=0&portrait=0&api=1&maxheight=480&maxwidth=800");

5 个答案:

答案 0 :(得分:11)

这个答案仅针对Vimeo。经过大约12次失败的尝试,这就是我的工作。也许它会帮助别人。向其他SO答案的原始作者致歉。我已经“借用”了下面的一些模式 - 只是认为将所有这些放在一个地方会很方便,并且不会为我自己的代码声明它们。

首先,我还没有找到一种方法来嵌入Vimeo播放器(即你不能直接进入mp4流 - 至少不容易或不可靠 - 我很确定这是故意的)。其次,Vimeo提供了一个javascript库来监控他们的播放器,使用它是相当不可避免的。请注意,它需要消息传递,这是一个较新的浏览器功能。这在他们的API页面上有记录。第三,正如SO上其他地方所记载的那样,你需要非常小心地等待堆栈的某些部分准备就绪,并且不要用枪跳。第四,Vimeo播放器包含一个特别无用的背景图像,旨在表明插件丢失或损坏(一小部分电影,常见的图标)。真正意味着你的javascript已经被某个地方轰炸了,而且什么都没有运行。如果你在空白屏幕上看到一点点电影,请检查你的javascript。

步骤1.设置WebView。你上面有这个正确的。作为参考,这是我使用的。

mWebView = new WebView((Context) this);
mWebView.setLayoutParams(new LayoutParams(windowWidth, windowHeight));

mWebView.getSettings().setJavaScriptEnabled(true);
 // Watch the sdk level here, < 12 requires 'false
 // Wanted to force HTML5/264/mp4, you may want flash
 //    where still available
mWebView.getSettings().setPluginState(PluginState.OFF);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setUserAgentString("Android Mozilla/5.0 AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");

wcc = new MyWebChromeClient();
mWebView.setWebChromeClient(wcc);

wvc = new MyWebViewClient();
mWebView.setWebViewClient(wvc);

步骤2.如果您希望视频在WebView上运行,则需要WebChromeClient。这里记录了:http://developer.android.com/reference/android/webkit/WebView.html(请参阅HTML视频支持)。

再次,这里是我用的参考。

private class MyWebChromeClient extends WebChromeClient {
    @Override
    public void onProgressChanged(WebView view, int progress) {
        if(progress == 100) {
          // Your page is loaded, but not visible,
          // add whatever navigation elements you plan to use here.
          // N.B. these are JAVA, not JS nav elements
        }
    }

    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {

     // I like to watch in the console. And, since it was
     // a very convenient way to monitor the javascript, I
     // use it for that too. Purists will object, no doubt

       if(cm.message().equalsIgnoreCase("EVENT -- Finish")) {
            Log.i(TAG, "---> Finishing . . .");
            // Depart the activity
            finish();
       } else {
            Log.d(TAG, " **Console ["+cm.sourceId()+"] ("+cm.lineNumber()+") ["+cm.message()+"]");
       }
       return(true);
   }

       @Override
       public View getVideoLoadingProgressView() {
                        // Something entertaining while the bytes arrive
            Log.i(TAG, " -------------> Loading Progress . . . ");
            LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return(inflater.inflate(R.layout.loading_video, null));
       }

       @Override
       public void onShowCustomView(View v, WebChromeClient.CustomViewCallback callback) {
                       // With great sadness, I report that this never fires.
                       // Neither does the 'hide'.
       }

       @Override
       public void onHideCustomView() {
       }

}

WebViewClient看起来像这样:

private class MyWebViewClient extends WebViewClient {

    @Override
    public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String injection = injectPageMonitor();
            if(injection != null) {
            Log.d(TAG, " ---------------> Page Loaded . . .");
                Log.d(TAG, "  Injecting . . . ["+injection+"]");
                view.loadUrl(injection);
            }
    }

}

步骤3.您需要构建一小部分Javascript来激活播放器。我用过这个:

public String injectPageMonitor() {
   return( "javascript:" +
               "jQuery(document).ready( function() { " +
               "console.log(' === Page Ready ===> Setting up');" +
               "console.log(' ==== Sending PLAY Command ===');" +
               "var froogaloop = $f('froog');" +
               "setTimeout(function() {  froogaloop.api('play'); }, 3000);" +
  "});");
}

快速解释。 。 。我在我的JS中使用jQuery,这将在下面。这只是为了方便,如果你想减轻负担,你可以直接做JS。请注意,在其他所有内容准备就绪后,脚本会等待另外3秒钟才能实际触发。在我较弱的时刻,我想Vimeo的善良人士有一个破碎的“准备好”的回调。 3秒似乎就这样做了。

步骤4.您需要在页面上添加一些HTML和JavaScript。我把它放在资源里面的一个文本文件中(raw / vimeo_frame.html)。该文件如下所示:

<!DOCTYPE html>
<html>
<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">jQuery.noConflict();</script>
<script src="http://a.vimeocdn.com/js/froogaloop2.min.js"></script>

<script type="text/javascript">

   jQuery(document).ready( function() { 
       var showing_player = false;
       var froogaloop = $f('froog');

           console.log(' === Page Ready ===> Setting up');
       jQuery('.froog_container_class').hide();
       jQuery('.console').css('height', '100%');

       froogaloop.addEvent('ready', function() { 

             console.log('====  PLAYER READY ====> Setting Play Callback');
                froogaloop.addEvent('play', function(data) { 
                console.log('EVENT -- Play');
                /* No idea why, but if the player isn't displayed, it goes
                   straight to 'pause'. Probably a feature. So I give it 4x4px
                   to do it's thing during setup */
                jQuery('.froog_container_class').show();
                jQuery('.froog_container_class').css('height', '4px');
                jQuery('.froog_container_class').css('width', '4px');
                jQuery('.froog_container_class').css('overflow', 'hidden');
            });

           /* I don't want to reveal the video until it is actually
              playing. So I do that here */
           var showingPlayer = false;
           froogaloop.addEvent('playProgress', function(data) {
               if(!showingPlayer && data.percent > 0) {
                  showingPlayer = true;
                  jQuery('.froog_container_class').show();
                  jQuery('.froog_container_class').css('height', '_windowHeight');
                  jQuery('.froog_container_class').css('width', '_windowWidth');
                  /* Most tablets I tested aren't quick enough to make this work
                     but one can still hope */
                  jQuery('#loading').fadeOut('slow');
               }
           });

       });
});
</script>
</head>
<body>
<style>
  body {
     background-image: url('http://<SomethingEntertainingToWatch>.png');
     background-size: contain;
  }
  .mask {
     float: left;
     height: _windowHeight;
     width: _windowWidth;
     z-index: 100;
     background: transparent;
     display: inline;
     position: absolute;
     top: 0;
     left: 0;
   }
   .froog_container_class {
      position: absolute;
      height: _windowHeight;
      width: _windowWidth;
      left: 0;
      top: 0;
      display: inline;
      z-index: 1;
    }
    #froog {
      display: inline;
      height: _windowHeight;
      width: _windowWidth;
      postion: absolute;
      top: 0;
      left: 0;
    }
</style>
<div id="loading" class="loading"><h1>Loading</h1><img class="loading_anim" src="http://foo.bar.com/assets/global/loading.gif"/>
</div>
<!-- Completely optional, I put a div in front of the player to block controls -->
<div id="mask" class="mask">
</div>
<div id="froog_container" class="froog_container_class">
   <iframe id="froog" src="_targetUrl?api=1&title=0&byline=0&portrait=0&player_id=froog" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen>
   </iframe>
</div>
</body>
</html>

我像这样加载这个html文件:

public String genMainHTML() {
    String code = null;
    try {
        Resources res = getResources();
        InputStream in_s = res.openRawResource(R.raw.vimeo_frame);

        byte[] b = new byte[in_s.available()];
        in_s.read(b);
        code = new String(b);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if(code != null) {
            code = code.replaceAll("_windowHeight", "" + windowHeight + "px");
            code = code.replaceAll("_windowWidth", "" + windowWidth + "px");
            code = code.replaceAll("_targetUrl", targetUrl);
            return(code);
    }  else  {
            return(null);
    }
}

并像这样注入:

mDomain = "http://player.vimeo.com";
mWebView.requestFocus(View.FOCUS_DOWN);
targetUrl = extras.getString("URL");
String meat = genMainHTML();
mWebView.loadDataWithBaseURL(mDomain, meat, "text/html", "utf-8", null);

setContentView(mWebView);

呼!当WebView准备就绪时,html和js会进入,包括带有Vimeo播放器的iframe。加载文档后,我们等待播放器准备就绪。当播放器准备就绪时,我们会添加一些听众。 3秒钟后,我们开启了api'play'方法。

观众中的那些苹果抛光者可能想知道,为了完整起见,如何停止视频?两位。首先,当它结束时,我通过观察控制台输出来显示我显示的消息来停止它。因此:

public String injectPageFinisher() {
    return( "javascript:" +
            "jQuery(document).ready( function() { " +
              "console.log(' === Page Ready ===> Tearing down');" +
              "console.log(' ==== Sending PAUSE Command ===');" +
              "var froogaloop = $f('froog');" +
          "froogaloop.api('pause');" +
              "jQuery('#froog_container').html('');" +
            "});");
    }

可以像这样插入:

@Override
public void onPause() {
    super.onPause();
    if(isFinishing()){
        // Unload the page
        if(mWebView != null) {
            Log.i(TAG, " ------> Destroying WebView");
            mWebView.destroy();
        }
    }
    finish();
}

第二位是视频完成其自我的小地方。因此,在上面的vimeo_frame.html中,在'play'回调之后,我把:

froogaloop.addEvent('finish', function(data) { 
    console.log('EVENT -- Finish');
});

在Activity中,我稍微注意了一下 - 参见上面的onConsoleMessage覆盖。

然而 - 在撰写本文时,我仍然没有排除一个棘手的问题。在WebView及其所有后代都消失之后,MediaPlayer继续存在。我确信这会产生一些问题,但我还没有发现它们。

答案 1 :(得分:8)

我们遇到了同样的问题,似乎Android WebView(以及iOS上的那些)没有编程允许自动启动视频,因为它可能会吃掉某些人流量套餐。你必须真正点击它,除非你想以谷歌的WebView为出发点并自己动手。它并不像听起来那么容易,我们试过了!

答案 2 :(得分:0)

我有同样的问题,我认为你可以使用这个来实现它:

  

public abstract void setMediaPlaybackRequiresUserGesture(boolean   需要)

     

在API级别17中添加设置WebView是否需要用户手势   玩媒体默认值为true。

     

参数要求WebView是否需要播放用户手势   媒体

希望至少帮助你一点!

答案 3 :(得分:0)

这是简单的解决方案

第1步,请确保您拥有minSdkVersion 17

Step2- mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);将此行粘贴到Vimeo类上。

答案 4 :(得分:0)

希望这可能对新手有所帮助。 请尝试将以下设置用于您的Web视图。

WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setMediaPlaybackRequiresUserGesture(false);

然后在您的Vimeo视频网址中附加autoplay = 1

webView.loadUrl(resLink + "?autoplay=1");

在这里,resLink看起来像“ https://player.vimeo.com/video/your_video_id”