android - 如何在 Amazon Fire TV 的 WebView 中播放 YouTube 视频?

标签 android video webview youtube amazon-fire-tv

我想在 Amazon Fire TV 的 WebView 中播放 YouTube 视频。

到今天为止,还没有用于在 Fire OS 上播放 YouTube 视频的官方 API (link),所以我尝试让它与 Android 的 WebView 一起工作。在Android WebView它编写的文档,该应用程序需要打开硬件加速,并且 WebView 需要有一个 WebChromeClient 才能播放 YouTube 视频。

我试图让它工作,但是当我开始播放 YouTube 视频时,我只看到全屏模式下的加载微调器。

这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  WebView webview = new WebView(this);
  setContentView(webview);

  webview.getSettings().setBuiltInZoomControls(true);
  webview.getSettings().setJavaScriptEnabled(true);
  webview.setWebChromeClient(new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
      Log.i("fire-tv", "Show custom view");

      super.onShowCustomView(view, callback);
      if (view instanceof FrameLayout) {
        FrameLayout frame = (FrameLayout) view;
        if (frame.getFocusedChild() instanceof VideoView) {
          VideoView video = (VideoView) frame.getFocusedChild();
          frame.removeView(video);
          setContentView(video);
          video.start();
        }
      }
    }

    @Override
    public void onHideCustomView() {
      Log.i("fire-tv", "Hide custom view.");
    }

  });

  webview.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return false;
    }

  });

  final String mimeType = "text/html";
  final String encoding = "UTF-8";
  String html = getHTML();

  Log.i("fire-tv", "Loading: " + html);
  webview.loadDataWithBaseURL("", html, mimeType, encoding, "");
}

private String getHTML() {
  String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 100%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
          + "h11u3vtcpaY"
          + "?fs=0\" frameborder=\"0\">\n"
          + "</iframe>\n";

  return html;
}

最佳答案

我编写了一个类来在 Fire TV 上播放 youtube 视频,它也适用于 kindle fire。如您所知,Youtube 没有官方 api,我们必须为此求助于 webviews。我粘贴在这里的类(class)除了 webview 之外还有很多你可能会好奇的东西,所以我会解释一下。首先,你会发现当你离开你的 Activity 时,一个 YouTube 播放的 webview 会继续播放,除非你告诉它停止。所以人家告诉别人的解决办法就是用onPause和pauseTimers方法关闭视频。但是有一个亚马逊强加给我们的令人讨厌的问题,那就是音频和视频资源没有发布到操作系统的其余部分(不是谷歌安卓 Lolipop 的问题,即 Nexus Player)。当资源被您的应用占用时,prime video 将无法播放,亚马逊将不允许您的应用上架。他们非常清楚我们必须为 youtube 使用 webview,所以他们给了我们一点建议:

Q: Can I use an Android WebView and the HTML tag for video playback?
A: Yes, with limitations. Hardware media resources are not currently released by the system when your app pauses or stops. To work around this issue implement your onStop() method to explicitly kill the process for your app:

Amazon source

就像 AVGN 会说“他们在想什么??”

您不会相信仅仅强行终止一个应用程序或 Activity 会导致大量问题......好吧,我相信您会相信,因为您比我多了几千分。

我能找到的唯一解决方案是在 onPause 方法中加载一个非常短的 720p 高清剪辑(必须有音频!)。我将它与 webView.onPause 和 .pauseTimers 结合使用以确保...

如果你使用这个类,请将我的 blank.mp4 文件复制到你自己的服务器,因为它可能在一个月内不存在。

哦,但还有更多。所以你在你的 webView 中获取你的 YouTube 文件......小菜一碟吧?错了,它不播放,因为在 webViews 中,Html5 通常从不自动播放。您不能将 url 设置为自动播放,这没有区别。所以我的解决方案是使用 java 技巧强制点击。它的工作方式是 webview 不会立即加载,完全加载需要不同的时间。完成后,视频会在屏幕中央显示一个播放按钮图标。由于某种原因,小 Remote 无法触摸它。但是我输入了代码以强制单击 webview 的中心。

哦,还有一件事,您必须处理音频焦点,否则亚马逊将不允许您的应用程序出现在商店中。潘多拉可以在后台播放,除非你处理它。

为什么亚马逊为什么

package com.ohiovr.modules.youtube;


import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Point;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.Timer;
import java.util.TimerTask;



public class youtubeKindleWebView extends Activity {


    String StringYoutubeUrl;
    WebView webView;

    AFChangeListener hocusFocus;
    private String videoBlanker = "http://ohiovr.com/church_files/blank.mp4";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generic_web_view);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        //I used this line in an old and now not used live stream implimentation. It works so I didn't remove it. But you may 
        //want to see if it is nessisary:
        webSettings.setUserAgentString("Mozilla/5.0(iPhone;U;CPUiPhoneOS4_0likeMacOSX;en-us)AppleWebKit/532.9(KHTML,likeGecko)Version/4.0.5Mobile/8A293Safari/6531.22.7");


        webView.setWebViewClient(new Callback()); 
        webView.setWebChromeClient(new WebChromeClient());


    }

    class AFChangeListener implements AudioManager.OnAudioFocusChangeListener {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                // mp.pause();
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                //  mp.start();
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                //  mp.stop();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean handled = false;

        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                forceAClick();
                break;
            case KeyEvent.KEYCODE_BUTTON_A:
                // ... handle selections
                handled = true;
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                // ... handle left action
                handled = true;
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                // ... handle right action
                handled = true;
                break;
        }
        return handled || super.onKeyDown(keyCode, event);
    }


    public void forceAClick() {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Display display = getWindowManager().getDefaultDisplay();
                        Point size = new Point();
                        display.getSize(size);
                        int width = size.x;
                        int height = size.y;


                        // Obtain MotionEvent object
                        long downTime = SystemClock.uptimeMillis();
                        long eventTime = SystemClock.uptimeMillis() + 100;
                        float x = width / 2;
                        float y = height / 2;
                        // List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
                        int metaState = 0;
                        MotionEvent motionEvent = MotionEvent.obtain(
                                downTime,
                                eventTime,
                                MotionEvent.ACTION_DOWN,
                                x,
                                y,
                                metaState
                        );

                        webView.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                Log.d("on touch", "touched down");
                                return false;
                            }
                        });

                        webView.dispatchTouchEvent(motionEvent);
                    }
                });
            }
        }, 1);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Display display = getWindowManager().getDefaultDisplay();
                        Point size = new Point();
                        display.getSize(size);
                        int width = size.x;
                        int height = size.y;


                        // Obtain MotionEvent object
                        long downTime = SystemClock.uptimeMillis();
                        long eventTime = SystemClock.uptimeMillis() + 100;
                        float x = width / 2;
                        float y = height / 2;
                        // List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
                        int metaState = 0;
                        MotionEvent motionEvent = MotionEvent.obtain(
                                downTime,
                                eventTime,
                                MotionEvent.ACTION_UP,
                                x,
                                y,
                                metaState
                        );

                        webView.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                Log.d("on touch", "touched up");
                                return false;
                            }
                        });

                        webView.dispatchTouchEvent(motionEvent);


                    }
                });
            }
        }, 120);


        AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
        hocusFocus = new AFChangeListener();
        int result = am.requestAudioFocus(hocusFocus, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }


    @Override
    public void onResume() {
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
        StringYoutubeUrl = "https://www.youtube.com/embed/" + getIntent().getStringExtra("youtubeID");
        webView.loadUrl(StringYoutubeUrl);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }


    private class Callback extends WebViewClient {  //this is important for some reason. don't remove!
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return (false);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();

        webView.loadUrl(videoBlanker);
        webView.pauseTimers();
        webView.onPause();
    }



    /*
    Q: Can I use an Android WebView and the <video> HTML tag for video playback?
    A:
    Yes, with limitations. Hardware media resources are not currently released by the system when your app pauses or stops. To work around this issue implement your onStop() method to explicitly kill the process for your app:

    https://developer.amazon.com/public/solutions/devices/fire-tv/docs/amazon-fire-tv-sdk-frequently-asked-questions
    public void onStop() {
        super.onStop();
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    This issue may also cause instability in the user experience and navigation for your app. The VisualOn SDK is the recommended method for media playback on the device.
    */

    @Override
    protected void onStop() {
        super.onStop();
        // the fascinating part of the next line is that it doesn't kill the application, only this intent
        /////////////  android.os.Process.killProcess(android.os.Process.myPid());
        //no no no! Amazon's advice is bad. It causes a ton of problems.
        //the original problem was that the webview video view frankenhybrid wouldn't release the
        //hardware when the user left the video player.
        //the only and correct solution is to load a very short quiet clip into the webview
        //when the user leaves
        //see onPause for my implementation

    }


}

关于android - 如何在 Amazon Fire TV 的 WebView 中播放 YouTube 视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27095552/

相关文章:

java - 无法解析 WifiManager 类中的公共(public)方法 setFrequencyBand

ios - 在 iOS 上使用 Phonegap 播放 mp4 视频

android - 出现键盘时 Webview 不调整大小

android - 单击 Webview 中的 textview 会导致屏幕跳转和 Webview 滚动变为无限

android - Android webView 中的阿拉伯语自定义字体

android - 如何修复 "TextInputLaout with TextInputEditText view I can not implement to show next focus Edittext using imeOption and nextFocustDown attribute"

android - 如何修复 ' Manifest merger failed with multiple errors,' 错误?

android - 使用工具栏中的 SearchView 自动打开/关闭键盘

html - 如果标题高度为 : 100vh,标题背景视频会调整大小

windows - 将音视频RTP数据合并成mp4文件