在Android应用中嵌入Youtube视频

时间:2022-11-27 16:51:27

I'm using a WebView for displaying embedded Youtube video and that works on Galaxcy S2 (OS 2.3.5) and doesn't on Nexus S (OS 2.3.4), all I get is white screen without any video display.

我正在使用WebView显示嵌入式Youtube视频并且可以在Galaxcy S2(OS 2.3.5)上运行而在Nexus S(OS 2.3.4)上运行,我得到的只是白屏而没有任何视频显示。

Here is the code snippet I'm using and the declarations in Manifest file:

这是我正在使用的代码片段和Manifest文件中的声明:

private WebView wv;

private void setWebView()
{
wv = (WebView) findViewById(R.id.webView);

wv.setWebChromeClient(new WebChromeClient());

wv.getSettings().setPluginState(WebSettings.PluginState.ON);

wv.setWebViewClient(new WebViewClient()); 

wv.getSettings();

wv.setBackgroundColor(0x00000000);

wv.setKeepScreenOn(true);

wv.setHorizontalScrollBarEnabled(false);
wv.setVerticalScrollBarEnabled(false);

wv.getSettings().setBuiltInZoomControls(true);

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

wv.loadDataWithBaseURL("", html, mimeType, encoding, "");

}


public String getHTML()
{

String html = "<html>"

    + "<head>"
 + "</head>"
 + "<body style=\"border: 0; padding: 0\">"
 + "<iframe "
 + "type=\"text/html\" "
 + "class=\"youtube-player\" "
 + "width= 100%\""
 + "\" "
 + "height= 95%\""
 + "\" "
 + "src=\"http://www.youtube.com/v/"
 + selected_video 
    + "?controls=0&showinfo=0&showsearch=0&modestbranding=0" +
 "&autoplay=1&fs=1&vq=hd720\" " + "frameborder=\"0\"></iframe>" 
    + "</body>"
    + "</html>";

 return html;
}

Note: the parameter "selected_video" is the hash of the video (VideoID).

注意:参数“selected_video”是视频的散列(VideoID)。

The declarations in Manifest file:

清单文件中的声明:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
.
.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"  />

<application
   .
   .
    android:hardwareAccelerated="true"  >

    .
    .

Please let me know in case you recognizing anything I should change in my code, or help with a complete code which can support all Android devices and OS for displaying embedded (In-App) Youtube video with high quality.

如果您在我的代码中识别出我应该更改的任何内容,请帮助我,或者帮助我们完整的代码,这些代码可以支持所有Android设备和操作系统,以显示高质量的嵌入式(In-App)Youtube视频。

UPDATE: Pay attention, the solution I'm looking for should display high resolution video. I got it work on the different devices and OS using VideoView class but the video quality isn't good enough. So any solution including VideoView or WebView or any other way will be accepted only if it makes high quality YouTube video to be displayed. Thanks to all the responders!

更新:注意,我正在寻找的解决方案应该显示高分辨率视频。我使用VideoView类在不同的设备和操作系统上工作,但视频质量不够好。因此,只有在显示高质量的YouTube视频时才会接受包括VideoView或WebView或任何其他方式的任何解决方案。感谢所有响应者!

8 个解决方案

#1


36  

there is an official YouTube Android Player API wich you can use. This is a bit more complicated but it is working better than other solutions using webclients.

您可以使用官方的YouTube Android播放器API。这有点复杂,但它比使用webclients的其他解决方案更好。

First you must register your app in Googles API Console. This is completely free until your app gets over 25k request a month (or something like that). There are complete anf great tutorials under the link. I hope you can understand them. If not, ask! :)

首先,您必须在Googles API控制台中注册您的应用。这是完全免费的,直到你的应用程序一个月超过25k请求(或类似的东西)。链接下有完整的anf很棒的教程。我希望你能理解它们。如果没有,请问! :)

#2


4  

although I suggest to use youtube api or call new intent and make the system handle it (i.e. youtube app), here some code that can help you, it has a call to an hidden method because you can't pause and resume webview

虽然我建议使用youtube api或调用新意图并使系统处理它(即youtube app),这里有一些可以帮助你的代码,它有一个隐藏方法的调用因为你无法暂停和恢复webview

import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import android.app.Activity;

@SuppressLint("SetJavaScriptEnabled")
public class MultimediaPlayer extends Activity
{
    private WebView mWebView;
    private boolean mIsPaused = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        String media_url = VIDEO_URL;

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebChromeClient(new WebChromeClient());

        WebSettings ws = mWebView.getSettings();
        ws.setBuiltInZoomControls(true);
        ws.setJavaScriptEnabled(true);

        mIsPaused = true;
        resumeBrowser();
        mWebView.loadUrl(media_url);
    }

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

    @Override
    protected void onResume()
    {
        resumeBrowser();
        super.onResume();
    }

    private void pauseBrowser()
    {
        if (!mIsPaused)
        {
            // pause flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onPause");
            mWebView.pauseTimers();
            mIsPaused = true;
        }
    }

    private void resumeBrowser()
    {
        if (mIsPaused)
        {
            // resume flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onResume");
            mWebView.resumeTimers();
            mIsPaused = false;
        }
    }

    private void callHiddenWebViewMethod(final WebView wv, final String name)
    {
        try
        {
            final Method method = WebView.class.getMethod(name);
            method.invoke(mWebView);
        } catch (final Exception e)
        {}
    }
}

#3


3  

It works like this:

它的工作原理如下:

String item = "http://www.youtube.com/embed/";

String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);

try {
    wv.loadData(
    "<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
    + (w1 - 20)
    + "\" height=\""
    + h1
    + "\" src=\""
    + item
    + "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
                            "text/html5", "utf-8");
} catch (Exception e) {
    e.printStackTrace();
}

private WebChromeClient chromeClient = new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        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);
                video.start();
            }
        }

    }
};

#4


1  

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

在Android中嵌入YouTube播放器非常简单,几乎不需要10分钟,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

以下是详细步骤http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html。

Just refer it & if you face any problem, let me know, ill help you

只要参考它,如果你遇到任何问题,请告诉我,不要帮助你

#5


1  

How it looks:

看起来如何:

在Android应用中嵌入Youtube视频

Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:

我的案例的最佳解决方案。我需要视频适合网页视图大小。将youtube链接与您的视频ID一起使用。例:

WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";

outubeWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });

WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);

youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);

Web view xml code

Web查看xml代码

<WebView
        android:id="@+id/youtube_web_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>

#6


0  

The video quality depends upon the Connection speed using API

视频质量取决于使用API​​的连接速度

alternatively for other than API means without YouTube app you can follow this link

或者,除了没有YouTube应用程序的API以外,您可以点击此链接

#7


0  

Refer to this answer: How can we play YouTube embeded code in an Android application using webview?

请参阅此答案:我们如何使用webview在Android应用程序中播放YouTube嵌入式代码?

It uses WebViews and loads an iframe in it... and yes it works.

它使用WebViews并在其中加载iframe ......是的,它可以工作。

#8


-1  

Use this Youtube Embed API from google.

从谷歌使用这个Youtube Embed API。

#1


36  

there is an official YouTube Android Player API wich you can use. This is a bit more complicated but it is working better than other solutions using webclients.

您可以使用官方的YouTube Android播放器API。这有点复杂,但它比使用webclients的其他解决方案更好。

First you must register your app in Googles API Console. This is completely free until your app gets over 25k request a month (or something like that). There are complete anf great tutorials under the link. I hope you can understand them. If not, ask! :)

首先,您必须在Googles API控制台中注册您的应用。这是完全免费的,直到你的应用程序一个月超过25k请求(或类似的东西)。链接下有完整的anf很棒的教程。我希望你能理解它们。如果没有,请问! :)

#2


4  

although I suggest to use youtube api or call new intent and make the system handle it (i.e. youtube app), here some code that can help you, it has a call to an hidden method because you can't pause and resume webview

虽然我建议使用youtube api或调用新意图并使系统处理它(即youtube app),这里有一些可以帮助你的代码,它有一个隐藏方法的调用因为你无法暂停和恢复webview

import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import android.app.Activity;

@SuppressLint("SetJavaScriptEnabled")
public class MultimediaPlayer extends Activity
{
    private WebView mWebView;
    private boolean mIsPaused = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        String media_url = VIDEO_URL;

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebChromeClient(new WebChromeClient());

        WebSettings ws = mWebView.getSettings();
        ws.setBuiltInZoomControls(true);
        ws.setJavaScriptEnabled(true);

        mIsPaused = true;
        resumeBrowser();
        mWebView.loadUrl(media_url);
    }

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

    @Override
    protected void onResume()
    {
        resumeBrowser();
        super.onResume();
    }

    private void pauseBrowser()
    {
        if (!mIsPaused)
        {
            // pause flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onPause");
            mWebView.pauseTimers();
            mIsPaused = true;
        }
    }

    private void resumeBrowser()
    {
        if (mIsPaused)
        {
            // resume flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onResume");
            mWebView.resumeTimers();
            mIsPaused = false;
        }
    }

    private void callHiddenWebViewMethod(final WebView wv, final String name)
    {
        try
        {
            final Method method = WebView.class.getMethod(name);
            method.invoke(mWebView);
        } catch (final Exception e)
        {}
    }
}

#3


3  

It works like this:

它的工作原理如下:

String item = "http://www.youtube.com/embed/";

String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);

try {
    wv.loadData(
    "<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
    + (w1 - 20)
    + "\" height=\""
    + h1
    + "\" src=\""
    + item
    + "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
                            "text/html5", "utf-8");
} catch (Exception e) {
    e.printStackTrace();
}

private WebChromeClient chromeClient = new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        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);
                video.start();
            }
        }

    }
};

#4


1  

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

在Android中嵌入YouTube播放器非常简单,几乎不需要10分钟,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

以下是详细步骤http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html。

Just refer it & if you face any problem, let me know, ill help you

只要参考它,如果你遇到任何问题,请告诉我,不要帮助你

#5


1  

How it looks:

看起来如何:

在Android应用中嵌入Youtube视频

Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:

我的案例的最佳解决方案。我需要视频适合网页视图大小。将youtube链接与您的视频ID一起使用。例:

WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";

outubeWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });

WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);

youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);

Web view xml code

Web查看xml代码

<WebView
        android:id="@+id/youtube_web_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>

#6


0  

The video quality depends upon the Connection speed using API

视频质量取决于使用API​​的连接速度

alternatively for other than API means without YouTube app you can follow this link

或者,除了没有YouTube应用程序的API以外,您可以点击此链接

#7


0  

Refer to this answer: How can we play YouTube embeded code in an Android application using webview?

请参阅此答案:我们如何使用webview在Android应用程序中播放YouTube嵌入式代码?

It uses WebViews and loads an iframe in it... and yes it works.

它使用WebViews并在其中加载iframe ......是的,它可以工作。

#8


-1  

Use this Youtube Embed API from google.

从谷歌使用这个Youtube Embed API。