YouTube Video no se reproduce en WebView – Android

Estoy atando para jugar el vídeo de YouTube en WebView, WebView que demuestra la primera mirada del vídeo con el botón del juego, pero después de chascar encendido la barra de progreso del comienzo del botón del juego y después de 2-3 segundos paran la barra de progreso y la pantalla en blanco con color negro.

Image1: Primer vídeo con el botón de reproducción

Image2: Después de hacer clic en el botón de reproducción la pantalla se queda en blanco.

¡Por favor! Ayúdame por qué el video no comienza.

IMAGEN: 1 Esta es la primera vista de la vista web

IMAGEN: 2 Introduzca aquí la descripción de la imagen

Este es mi código fuente para reproducir YouTubeVideo en webview .. Por favor, ayúdame …

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView wv = (WebView) findViewById(R.id.webView1); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setPluginsEnabled(true); final String mimeType = "text/html"; final String encoding = "UTF-8"; String html = getHTML(); wv.loadDataWithBaseURL("", html, mimeType, encoding, ""); } public String getHTML() { String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/" + "J2fB5XWj6IE" + "?fs=0\" frameborder=\"0\">\n" + "</iframe>\n"; return html; } 

Agregue estas líneas antes de cargar contenido HTML en su WebView.

 wv.setWebChromeClient(new WebChromeClient() { }); 

De la documentación:

Para admitir el vídeo HTML5 en línea en su aplicación, debe activar la aceleración de hardware y establecer un WebChromeClient . Para el soporte de pantalla completa, las implementaciones de onShowCustomView (View, WebChromeClient.CustomViewCallback) y onHideCustomView () son obligatorias, getVideoLoadingProgressView () es opcional.

El siguiente código es necesario para mostrar el reproductor de video que se inicia con el framework web core. La clave para todo el flujo es que el VideoView se devuelve al WebChromeClient y debe adjuntar esa vista a la jerarquía de su vista.

Lo he montado a través de revisar el código fuente del navegador disponible como parte de la AOSP.

Este código hace referencia a 4 vistas que pueden no ser obvias. La jerarquía de vista es:

  • FrameLayout mContentView (raíz)
  • WebView mWebView (hijo de mContentView)
  • FrameLAyout mCustomViewContainer (hijo de mContentView)
  • View mCustomView (hijo de mCustomViewContainer)

Las vistas se configuran como parte de la configuración de la actividad del contenedor.

 <FrameLayout android:id="@+id/fullscreen_custom_content" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FF000000"/> <FrameLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > <WebView android:id="@+id/webView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </FrameLayout> </FrameLayout> 

En sus Actividades onCreate :

  mContentView = (FrameLayout) findViewById(R.id.main_content); mWebView = (WebView) findViewById(R.id.webView); mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content); 

Registre un WebChromeClient con mWebView . Ese cliente debe anular los siguientes 2 – 4 métodos:

 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { // if a view already exists then immediately terminate the new one if (mCustomView != null) { callback.onCustomViewHidden(); return; } // Add the custom view to its container. mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER); mCustomView = view; mCustomViewCallback = callback; // hide main browser view mContentView.setVisibility(View.GONE); // Finally show the custom view container. mCustomViewContainer.setVisibility(View.VISIBLE); mCustomViewContainer.bringToFront(); } void onHideCustomView() { if (mCustomView == null) return; // Hide the custom view. mCustomView.setVisibility(View.GONE); // Remove the custom view from its container. mCustomViewContainer.removeView(mCustomView); mCustomView = null; mCustomViewContainer.setVisibility(View.GONE); mCustomViewCallback.onCustomViewHidden(); // Show the content view. mContentView.setVisibility(View.VISIBLE); } public Bitmap getDefaultVideoPoster() { if (mDefaultVideoPoster == null) { mDefaultVideoPoster = BitmapFactory.decodeResource(getResources(), R.drawable.default_video_poster); } return mDefaultVideoPoster; } public View getVideoLoadingProgressView() { if (mVideoProgressView == null) { LayoutInflater inflater = LayoutInflater.from(this); mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null); } return mVideoProgressView; } 

También puede agregar enlaces de ciclo de vida de actividad como:

 @Override protected void onStop() { super.onStop(); if (mCustomView != null) { if (mCustomViewCallback != null) mCustomViewCallback.onCustomViewHidden(); mCustomView = null; } } @Override public void onBackPressed() { if (mCustomView != null) { onHideCustomView(); } else { finish(); } } 

A su actividad para que el vídeo se oculte cuando se detiene la actividad o se presiona el botón Atrás.

Añadir webview.setWebChromeClient(new WebChromeClient()); Y para habilitar complementos para tu video add

 if (Build.VERSION.SDK_INT < 8) { webview.getSettings().setPluginsEnabled(true); } else { webview.getSettings().setPluginState(PluginState.ON); } 

Thnaks

Hay algún problema con los videos youtbe transmitidos en los dispositivos móviles. Si intenta directamente cargar la URL en la vista web y ejecutarla, el video no se reproducirá. Una forma difícil de resolver este problema es transmitir el video en la vista de vídeo. No he intentado esto, pero esto se puede hacer.
Otra manera de reproducir los videos de youtube, voy a llamar a esto la manera más fácil es cambiar el agente de usuario en la configuración de la vista web desde el dispositivo móvil a un escritorio. Agente de usuario indica el tipo de dispositivo en el que se ejecutará el video de youtube y, en consecuencia, ese tipo de página web es enviada por el servidor. De esta manera, el video de youtube puede ser transmitido y reproducido. Aquí es cómo puede hacer esto:

 public static final int USER_MOBILE = 0; public static final int USER_DESKTOP = 1; wv.getSettings().setUserAgent(USER_DESKTOP); // 1 is for the desktop 

He copiado el código askers y funcionó para mí …. creo que tienes que instalar el pagador flash .. di u ?? Y u añadir permiso de internet ???

Btw mi código está aquí …

 package com.example.youtube; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import android.util.Log; import android.view.Menu; import android.view.Window; import android.view.WindowManager; import android.webkit.DownloadListener; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebChromeClient; import android.webkit.WebViewClient; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AbsoluteLayout; import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.os.AsyncTask; import android.util.Log; import android.widget.TextView; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; public class MainActivity extends Activity{ @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().requestFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.activity_main); final ProgressBar Pbar; Pbar = (ProgressBar) findViewById(R.id.pB4); WebView wv = (WebView) findViewById(R.id.webVie1); //wv.setWebViewClient(new Callback()); WebSettings webSettings = wv.getSettings(); webSettings.setBuiltInZoomControls(true); webSettings.setJavaScriptEnabled(true); //wv.setBackgroundColor(0x919191); final String mimeType = "text/html"; final String encoding = "UTF-8"; String html = getHTML(); wv.loadDataWithBaseURL("", html, mimeType, encoding, ""); final Activity activity = this; wv.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { // Activities and WebViews measure progress with different scales. // The progress meter will automatically disappear when we reach 100% activity.setProgress(progress * 100); { if(progress < 100 && Pbar.getVisibility() == ProgressBar.GONE){ Pbar.setVisibility(ProgressBar.VISIBLE); } Pbar.setProgress(progress); if(progress == 100) { Pbar.setVisibility(ProgressBar.GONE); } } } }); wv.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_LONG).show(); } }); wv.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimetype,long contentLength) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } }); } private String getHTML() { // TODO Auto-generated method stub String html1 = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/" + "J2fB5XWj6IE" + "?fs=0\" frameborder=\"0\">\n" + "</iframe>\n"; return html1; } /* public void onPause() { super.onPause(); System.exit(0); }*/ } 

Archivo de diseño

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/page_buttons" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="horizontal" > </LinearLayout> <WebView android:id="@+id/webVie1" android:layout_width="316dp" android:layout_height="392dp" android:layout_alignParentBottom="true" android:layout_alignParentTop="true" android:layout_weight="0.99" /> <ProgressBar android:id="@+id/pB4" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"/> /> </LinearLayout> 

¿Por qué quieres reproducirte tu video de tubo en la vista web? Puedes jugar con esta intención

 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(stringUrl))); 

De lo contrario, si desea reproducirlo en webView, siga este enlace

http://www.stackoverflow.com/questions/9565533/android-how-to-play-youtube-video-in-webview?rq=1

Intente esto

 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(stringUrl))); 
  • Implementar Youtube Subscribe Button en Android
  • la forma actual recomendada para reproducir vídeo de youtube en todos los dispositivos Android
  • YouTubeAndroidPlayerAPI no puede reproducir algunos videos
  • Error al ejecutar 'postMessage' en el mensaje 'DOMWindow' en Android
  • Intención de youtube app profile / channel
  • Excepción de clase no encontrada al ejecutar demostraciones de API de YouTube para Android
  • Detener el video de youtube después de 1-2 segundos
  • Detectar o la latencia aproximada de Bluetooth en Android (reproducción de audio)
  • Incorporar video de Youtube dentro de una aplicación para Android
  • Forzar el vídeo para abrir en la aplicación de Youtube en Android
  • API de YouTube de Android "Se ha producido un error al inicializar el reproductor de YouTube"
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.