2011-11-25 22 views
23

Quiero transmitir en vivo el video y está en formato m3u8. Así que he intentado el código de abajoReproducir video m3u8 en android

public class StreamingPlayer extends Activity implements 
OnBufferingUpdateListener, OnCompletionListener, 
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback{ 

    private static final String TAG = StreamingPlayer.class.getSimpleName(); 
    private int mVideoWidth; 
    private int mVideoHeight; 
    private MediaPlayer mMediaPlayer; 
    private SurfaceView mPreview; 
    private SurfaceHolder holder; 
    private String path; 

    private boolean mIsVideoSizeKnown = false; 
    private boolean mIsVideoReadyToBePlayed = false; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.mediaplayer_2); 
     mPreview = (SurfaceView) findViewById(R.id.surface); 
     holder = mPreview.getHolder(); 
     holder.addCallback(this); 
     holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
    } 

    private void playVideo() { 
     doCleanUp(); 
     try { 

      /* 
      * TODO: Set path variable to progressive streamable mp4 or 
      * 3gpp format URL. Http protocol should be used. 
      * Mediaplayer can only play "progressive streamable 
      * contents" which basically means: 1. the movie atom has to 
      * precede all the media data atoms. 2. The clip has to be 
      * reasonably interleaved. 
      * 
      */ 

      path = "httplive://xboodangx.api.channel.livestream.com/3.0/playlist.m3u8"; 

      if (path == "") { 
       // Tell the user to provide a media file URL. 
       Toast 
       .makeText(
         this, 
         "Please edit MediaPlayerDemo_Video Activity," 
         + " and set the path variable to your media file URL.", 
         Toast.LENGTH_LONG).show(); 
      } 

      Log.e("PATH", "Path = " + path); 
      // Create a new media player and set the listeners 
      mMediaPlayer = new MediaPlayer(); 
      mMediaPlayer.setDataSource(path); 
      mMediaPlayer.setDisplay(holder); 
        mMediaPlayer.setOnBufferingUpdateListener(this); 
        mMediaPlayer.setOnPreparedListener(this); 
      mMediaPlayer.prepare(); 
      mMediaPlayer.setOnCompletionListener(this); 
      mMediaPlayer.setOnVideoSizeChangedListener(this); 
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 

     } catch (Exception e) { 
      Log.e(TAG, "error: " + e.getMessage(), e); 
     } 
    } 

    public void onBufferingUpdate(MediaPlayer arg0, int percent) { 
     Log.d(TAG, "onBufferingUpdate percent:" + percent); 

    } 

    public void onCompletion(MediaPlayer arg0) { 
     Log.d(TAG, "onCompletion called"); 
    } 

    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { 
     Log.v(TAG, "onVideoSizeChanged called"); 
     if (width == 0 || height == 0) { 
      Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")"); 
      return; 
     } 
     mIsVideoSizeKnown = true; 
     mVideoWidth = width; 
     mVideoHeight = height; 
     if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) { 
      startVideoPlayback(); 
     } 
    } 

    public void onPrepared(MediaPlayer mediaplayer) { 
     Log.d(TAG, "onPrepared called"); 
     mIsVideoReadyToBePlayed = true; 
     if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) { 
      startVideoPlayback(); 
     } 
    } 

    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) { 
     Log.d(TAG, "surfaceChanged called"); 

    } 

    public void surfaceDestroyed(SurfaceHolder surfaceholder) { 
     Log.d(TAG, "surfaceDestroyed called"); 
    } 


    public void surfaceCreated(SurfaceHolder holder) { 
     Log.d(TAG, "surfaceCreated called"); 
     playVideo(); 

    } 

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

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     releaseMediaPlayer(); 
     doCleanUp(); 
    } 

    private void releaseMediaPlayer() { 
     if (mMediaPlayer != null) { 
      mMediaPlayer.release(); 
      mMediaPlayer = null; 
     } 
    } 

    private void doCleanUp() { 
     mVideoWidth = 0; 
     mVideoHeight = 0; 
     mIsVideoReadyToBePlayed = false; 
     mIsVideoSizeKnown = false; 
    } 

    private void startVideoPlayback() { 
     Log.v(TAG, "startVideoPlayback"); 
     holder.setFixedSize(mVideoWidth, mVideoHeight); 
     mMediaPlayer.start(); 
    } 


} 

En Logcat muestra onBufferingUpdate percent:100 pero no puedo ver el video.

El audio funciona, pero de repente fue golpeado.

Y probé este enlace de video http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8 está funcionando. Pero mi enlace de video no funciona y cambié httplive://... instead of http:// pero no uso.

Y vi esta respuesta también Android video stream mms and m3u8.

En el enlace de arriba se muestra El mensaje de video no se puede reproducir.

+0

¿Has probado probarlo en un dispositivo real? a veces el emulador es una mierda cuando se trata de HTTP Live Streaming. – yorkw

+0

@yorkw Gracias por su respuesta. Sí, lo probé en un dispositivo real, no en un emulador. – Ramakrishna

+0

El URI h t t p: //myvideo.m3u8 me parece extraño, ¿dónde aloja los medios? un servidor remoto? Si tiene acceso al código de transmisión en el lado del servidor, intente cambiarlo a una URL más sólida como h t t p: //nombre_de_dominio/nombre_servicio/myvideo.m3u8. no estoy seguro si esto funciona, pero vale la pena intentarlo. – yorkw

Respuesta

14

El video ya existía en http://www.livestream.com. En esto hay Mobile Api para transmisión en vivo.

El API es:

http://www.livestream.com/userguide/index.php?title=Mobile_API#How_to_get_mobile_compatible_clips_from_a_channel.27s_library

En enlace anterior se dispone de información completa para móviles compatibles. Para obtener el enlace RTSP desde el canal a utilizar este enlace

http://xproshowcasex.channel-api.livestream-api.com/2.0/getstream

Cambie el nombre de su canal en lugar de proshowcase. Y luego obtenga todas las url compatibles con dispositivos móviles como iPhone, Android, Blackberry, etc.,

Al usar esa url puede transmitir el video en Android usando la vista de video o el reproductor multimedia.

Para obtener más información, lea el enlace de Mobile Api.

Si alguien tiene el mismo problema, espero que esta respuesta lo ayude.

Lo mejor de la suerte.

+0

¿es posible ver el código funcionando? enfrentando el mismo problema –

+0

@GuillermoVarini El código anterior no me funciona. Por favor, lea mi respuesta y dígame su problema en detalle, entonces le diré que responda si lo sé. – Ramakrishna

+0

el problema es que necesito reproducir un video m3u8 en la aplicación 2.1 y no puedo encontrar un ejemplo real de cómo hacerlo. encontró 2 publicaciones aquí pero no funcionó. también se comprobó en developer.android.com/ pero nada: ¿Dices que con esta API esto funciona? tener un ejemplo de cómo implementarlo? –

1

creo que debe mover esto:

mMediaPlayer.setOnPreparedListener(this); 

que ser antes de la llamada a prepare()

+0

Gracias por su respuesta. Implementé su idea, pero no está funcionando. Hasta que aparezca onBufferingUpdate percent: 100 y no puedo ver el video – Ramakrishna

1

¿Se intenta reproducir su enlace con el reproductor nativo directamente a través del navegador web? Si no puede jugar con un reproductor nativo, significa que su archivo no es compatible con su versión actual de Android. El formato HTTP Live Streaming puede tener algunas características que no son bien compatibles con Android, mientras que puede jugar en IOS.

+0

Gracias por su respuesta. Está trabajando con Android Player nativo y en IOS también. Hay Ya completó esta tarea. – Ramakrishna

0

Probé el formato de video m3u8 durante más de 6 meses y no se realiza correctamente. Está jugando en mi aplicación de iPhone y aplicaciones nativas. Mi servidor de transmisión es Red5 y no tiene ningún complemento RTSP. Ofrece transmisión RTMP y no se pudo transmitir en Android. Esperé durante un año para obtener un sistema operativo con soporte para transmisión RTSP pero google no. Todavía estoy usando una vista web con un reproductor flash para transmitir video en vivo (no tiene mucha claridad). Siento vergüenza de decirle esto a mi cliente y continuar la búsqueda para reproducir la transmisión en vivo en el reproductor predeterminado de Android.

Creo que su URL de video no puede RTSP.

4

no tengo ningún problema para reproducir la secuencia:

videoView1.setVideoPath("http://***.net/livedemo/_definst_/stream3.stream/playlist.m3u8?wowzasessionid=773395207"); 
videoView1.start(); 

Acerca del mensaje:

El vídeo no se puede reproducir

Tal vez es necesario agregar permisos para el archivo de manifiesto :

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
+3

no es necesario. – Jorgesys

+0

Mismo problema. ¿Encontraste una solución? –

+0

Sergey

0

Cómo jugar .M3U8 Transmisión en Android

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" > 

    <VideoView 
     android:id="@+id/myVideoView" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

Main.java

package com.grexample.ooyalalive; 

import java.net.URL; 
import android.app.Activity; 
import android.net.Uri; 
import android.os.Bundle; 
import android.widget.MediaController; 
import android.widget.VideoView; 

public class Main extends Activity { 

    private String urlStream; 
    private VideoView myVideoView; 
    private URL url; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main_vv);//*************** 
      myVideoView = (VideoView)this.findViewById(R.id.myVideoView); 
      MediaController mc = new MediaController(this); 
      myVideoView.setMediaController(mc);   
      urlStream = "http://jorgesys.net/i/[email protected]/master.m3u8"; 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        myVideoView.setVideoURI(Uri.parse(urlStream)); 
       } 
      }); 
    } 
} 

He visto una gran cantidad de personas han problemas jugando .M3U8, depende de los códecs utilizados para la transmisión de una y compatibilidad con el dispositivo, por ejemplo, algunos de mis archivos .m3u8 solo se admiten en dispositivos con pantallas de 1200 x 800 o más.

+3

No necesita llamar a runOnUiThread dentro de onCreate, ya está en UI hilo – busylee

Cuestiones relacionadas