2011-01-29 29 views
18

Estoy reproduciendo archivos de video locales usando MediaPlayer y SurfaceView. SurfaceView es el único control en actividad, mientras que mis archivos de video son QVGA u otros. El problema es que el video se está estirando, ¿Cómo puedo reproducir el video en su tamaño original, p. qvga con área restante negra.Android: reproductor de medios: cómo usar SurfaceView o reproductor de medios para reproducir videos en el tamaño correcto

De iteración,

Cuando estoy enérgicamente establece layout_height/ancho de SurfaceView en XML, vídeo mostrado bien. surface_holder.setFixedSize(w,h) no tiene ningún efecto, ni mp.setdisplay().

Por favor guía en esto.

ACTUALIZACIÓN

flie XML

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/home_container" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent"> 

<SurfaceView 
     android:id="@+id/surface" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingTop="10dip" /> 
</framelayout> 

uso MediaPlayer es según siguiente enlace

http://davanum.wordpress.com/2007/12/29/android-videomusic-player-sample-from-local-disk-as-well-as-remote-urls/

Gracias de antemano.

Respuesta

-3

En su SurfaceView en XML, ¿está utilizando wrap_content? Esto debería arreglar tu problema si no. Es posible que necesite pegar un poco más de código para una investigación más profunda si eso no soluciona su problema.

Cambia el ancho de la vista de la superficie a wrap_content también.

+0

estoy usando wrap_content en XML, un Fuente dded. El video está en una pantalla completa, estirado, quiero mostrar el video en su tamaño original. – JRC

+0

He actualizado mi respuesta, por favor cambie su ancho para ajustar el contenido también. Con cualquiera de los dos configurados para llenar, el diseño extenderá el video proporcionalmente en cualquier dirección. – Joey

+0

Esto no funciona –

77

Al configurar su diseño de SurfaceView en wrap_content se no haga un tamaño de un video para reproducir en la relación de aspecto adecuada.

  • A SurfaceView es una superficie de dibujo optimizado
  • Un video se señala a un SurfaceView, no contenida dentro de ella

wrap_content es sinónimo de fill_parent para un SurfaceView.

Lo que quiere hacer es obtener las dimensiones de su video desde el objeto MediaPlayer. Luego puede establecer la relación de aspecto del SurfaceView para que coincida con el video.

Algunos inicialización básica

public class YourMovieActivity extends Activity implements SurfaceHolder.Callback { 
    private MediaPlayer mp = null; 
    //... 

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

     mp = new MediaPlayer(); 
     mSurfaceView = (SurfaceView) findViewById(R.id.surface); 
     //... 
    } 
} 

Entonces las cosas buenas. He omitido la comprobación de errores aquí para reducir el código, las llamadas a MediaPlayer deben incluirse en una prueba {}.

@Override 
public void surfaceCreated(SurfaceHolder holder) { 

    mp.setDataSource("/sdcard/someVideo.mp4"); 
    mp.prepare(); 

    //Get the dimensions of the video 
    int videoWidth = mp.getVideoWidth(); 
    int videoHeight = mp.getVideoHeight(); 

    //Get the width of the screen 
    int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); 

    //Get the SurfaceView layout parameters 
    android.view.ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams(); 

    //Set the width of the SurfaceView to the width of the screen 
    lp.width = screenWidth; 

    //Set the height of the SurfaceView to match the aspect ratio of the video 
    //be sure to cast these as floats otherwise the calculation will likely be 0 
    lp.height = (int) (((float)videoHeight/(float)videoWidth) * (float)screenWidth); 

    //Commit the layout parameters 
    mSurfaceView.setLayoutParams(lp);   

    //Start video 
    mp.start(); 
} 

Tenga en cuenta que este código hace algunas suposiciones sobre las dimensiones de su video. Tal como está, maximiza el ancho y supone que la altura no es mayor que la altura de la pantalla.

Es posible que desee ajustar la altura en lugar de la anchura, también puede verificar el cálculo de la dimensión y asegurarse de que no sea mayor que la pantalla o pantalla - other_layout_elements.

+2

No tengo palabras para agradecerle Error 454 ... Usted ha guardado mi proyecto ... – Farhan

+0

Me alegro de que esto haya funcionado :) –

+0

Nota: el getVideoWidth y getVideoHeight están invertidos en el ejemplo anterior – coco

3

Este es el código que uso actualmente en un proyecto:

private MediaPlayer mMediaPlayer; 
private SurfaceView mSurfaceView; 
private SurfaceHolder holder; 
private int mPos = 0; 

...

int width = mSurfaceView.getWidth(); 
int height = mSurfaceView.getHeight(); 
float boxWidth = width; 
float boxHeight = height; 

float videoWidth = mMediaPlayer.getVideoWidth(); 
float videoHeight = mMediaPlayer.getVideoHeight(); 

Log.i(TAG, String.format("startVideoPlayback @ %d - video %dx%d - box %dx%d", mPos, (int) videoWidth, (int) videoHeight, width, height)); 

float wr = boxWidth/videoWidth; 
float hr = boxHeight/videoHeight; 
float ar = videoWidth/videoHeight; 

if (wr > hr) 
    width = (int) (boxHeight * ar); 
else 
    height = (int) (boxWidth/ar); 

Log.i(TAG, String.format("Scaled to %dx%d", width, height)); 

holder.setFixedSize(width, height); 
mMediaPlayer.seekTo(mPos); 
mMediaPlayer.start(); 

la disposición que estoy usando (se puede simplemente ignorar la barra de progreso)

<?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:gravity="center" 
    android:orientation="vertical" > 

<ProgressBar 
    android:id="@+id/progressBar1" 
    style="?android:attr/progressBarStyleHorizontal" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

<SurfaceView 
    android:id="@+id/surface" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" > 
</SurfaceView> 

+0

quizás 'android.widget.VideoView' ya lo hace por sí mismo – sherpya

+0

por favor escriba el código completo ... no ha creado la instancia' MediaPlayer' y no ha mostrado la relación entre el titular y el reproductor multimedia. –

+0

Estoy usando 'VideoView' ahora, es un widget que puede usarlo directamente en el diseño, maneja la relación de aspecto por sí mismo – sherpya

Cuestiones relacionadas