2012-01-12 14 views
35

Necesito usar el video como mi fondo. Primero puse el archivo de video en una carpeta dibujable y llamé como fondo de LinearLayout en main.xml. Pero mientras ejecutaba la aplicación, solo vi una pantalla negra. Luego trató de utilizar VideoView y lo llamó como el siguiente:Integración de un archivo de video en la aplicación de Android como fondo de la aplicación

<VideoView 
    android:id="@+id/video" 
    android:layout_width="320px" 
    android:layout_height="240px" 
    android:layout_gravity="center" 
    android:background="@raw/hp"/> 

En mi fichero de actividad lo llamé con siguiente fragmento de código:

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

     setContentView(R.layout.main); 
     VideoView video=(VideoView) findViewById(R.id.video); 
     video.start(); 
} 

Pero todavía no estoy recibiendo el archivo de vídeo allí. Mi principal propuesta es utilizar un video de burbujas como fondo y colocar dos botones de burbujas en él para que el usuario se sienta como una pantalla de vista de agua. ¿Alguien puede ayudarme?

También el archivo de video que quiero usar de la carpeta res. No desde la tarjeta SD o cualquier carpeta externa de medios.

Respuesta

39

Bueno, amigo mío, antes que nada no puede establecer un fondo para su VideoView y hacer que se reproduzca en el fondo de su pantalla.

Por favor, sigue mis pasos y agrega tu esfuerzo y deberías estar ahí.

Elimine su video de la carpeta dibujable y agréguelo a la carpeta sin formato. Por favor google cómo crear una carpeta sin formato. Es simple sin embargo. Y pon tu archivo de video dentro.

Antes que nada, crea un SurfaceView en tu xml de esta forma.

<?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> 

Ahora, cree una clase como la de abajo que se puede aplicar SurfaceView,

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

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

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

Ahora su clase solicitará métodos no implementados para ser añadido. Añadir estos métodos con sólo hacer clic en "Añadir métodos no implementados"

Ahora usted será capaz de ver un método de auto generada de esta manera,

@Override 
public void surfaceCreated(SurfaceHolder holder) { 

} 

Y dentro de este método, añadir el código de abajo,

@Override 
public void surfaceCreated(SurfaceHolder holder) { 


    Uri video = Uri.parse("android.resource://" + getPackageName() + "/" 
     + R.raw.your_raw_file); 

    mp.setDataSource(video); 
    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.setDisplay(holder); 
    mp.start(); 
} 
+0

¿Hay alguna manera de que pudiera hacer lo mismo desde un servicio en segundo plano? ¿Como crear un reproductor de video del servicio? –

+0

¿Qué hay de 'TextureView'? @AndroSelva –

+3

Esto no funciona para mí, espero que alguien venga con una mejor solución o una forma eficiente de integrar un archivo de video. – XcodeNOOB

0

he utilizado

AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.file_name); 
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength()); 

en lugar de

Uri video = Uri.parse("android.resource://" + getPackageName() + "/" 
     + R.raw.your_raw_file); 

y usados ​​código de abajo a reproductor multimedia de configuración.

MediaPlayer mp = new MediaPlayer(); 
SurfaceView mSurfaceView = (SurfaceView) findViewById(R.id.video_surface); 
SurfaceHolder holder = mSurfaceView.getHolder(); 
holder.addCallback(this); 
14
/** 
* Created by zoid23 on 05/10/15. 
*/ 
public class IntroVideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback { 

    private static final String TAG = "INTRO_SF_VIDEO_CALLBACK"; 
    private MediaPlayer mp; 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    public IntroVideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 
     init(); 
    } 

    public IntroVideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     init(); 
    } 
    public IntroVideoSurfaceView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 
    public IntroVideoSurfaceView(Context context) { 
     super(context); 
     init(); 
    } 

    private void init(){ 
     mp = new MediaPlayer(); 
     getHolder().addCallback(this); 
    } 

    @Override 
    public void surfaceCreated(SurfaceHolder holder) { 
     AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.intro); 
     try { 
      mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength()); 
      mp.prepare(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     int videoWidth = mp.getVideoWidth(); 
     int videoHeight = mp.getVideoHeight(); 
     int screenHeight = getHeight(); 
     android.view.ViewGroup.LayoutParams lp = getLayoutParams(); 
     lp.height = screenHeight; 
     lp.width = (int) (((float)videoWidth/(float)videoHeight) * (float)screenHeight); 

     setLayoutParams(lp); 
     mp.setDisplay(getHolder()); 
     mp.setLooping(true); 
     mp.start(); 
    } 

    @Override 
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
    } 

    @Override 
    public void surfaceDestroyed(SurfaceHolder holder) { 
     mp.stop(); 
    } 

} 

Uso IntroVideoSurfaceView en su xml y poner el vídeo en raw/intro.mp4

+0

Tienes que cerrar afd. finalmente { try { afd.close(); } catch (IOException e) { e.printStackTrace(); } } –

6

La versión completa de la versión modificada de luigi23 con evitar algunos accidentes.

import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 

public class MainActivity extends AppCompatActivity { 

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

nada en la actividad. es posible que desee para que sea pantalla completa mediante la adición de

<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar"> 
    <item name="windowNoTitle">true</item> 
    <item name="windowActionBar">false</item> 
    <item name="android:windowFullscreen">true</item> 
    <item name="android:windowContentOverlay">@null</item> 
    </style> 

Crear un archivo IntroVideoSurfaceView.java

import android.annotation.TargetApi; 
import android.content.Context; 
import android.content.res.AssetFileDescriptor; 
import android.media.MediaPlayer; 
import android.os.Build; 
import android.util.AttributeSet; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 
import java.io.IOException; 

public class IntroVideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback { 

    private MediaPlayer mp; 
    private boolean has_started = false; 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) public IntroVideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
    super(context, attrs, defStyleAttr, defStyleRes); 
    init(); 
    } 

    public IntroVideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) { 
    super(context, attrs, defStyleAttr); 
    init(); 
    } 

    public IntroVideoSurfaceView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    init(); 
    } 

    public IntroVideoSurfaceView(Context context) { 
    super(context); 
    init(); 
    } 

    private void init() { 
    mp = new MediaPlayer(); 
    getHolder().addCallback(this); 
    } 

    @Override public void surfaceCreated(SurfaceHolder holder) { 
    AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.slideshow); 
    try { 
     if (!has_started) { 
     has_started = true; 
     mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength()); 
     } 

     mp.prepare(); 
     android.view.ViewGroup.LayoutParams lp = getLayoutParams(); 
     lp.height = getHeight(); 
     lp.width = getWidth(); 

     setLayoutParams(lp); 
     mp.setDisplay(getHolder()); 
     mp.setLooping(true); 
     mp.start(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

    @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
    } 

    @Override public void surfaceDestroyed(SurfaceHolder holder) { 
    mp.stop(); 
    } 
} 

añadir un "slideshow.mp4" en recursos/primas

modifique el activity_main.xml con

<?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" 
    > 

    <com.androidadvance.videobackground.IntroVideoSurfaceView 
     android:id="@+id/surface" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Press Me" 
     android:id="@+id/button" 
     android:layout_gravity="center_horizontal|bottom" 
     android:layout_margin="16dp" 
     /> 
</FrameLayout> 

Algunas notas.

Adición de un video hará que su apk enorme así que es posible que desee evitar esto ... De vez en cuando los accidentes ocurren desconocidos, incluso en los teléfonos de gama alta (Galaxy S6) Es esencial para mantener el archivo pequeño.

+2

Este código funciona cuando se crea y se ejecuta la actividad. Pero cuando vamos a la siguiente actividad y volvemos a esto, falla con un error como: java.lang.IllegalStateException en android.media.MediaPlayer._prepare (método nativo) en android.media.MediaPlayer.prepare (MediaPlayer.java:1135) en – techtinkerer

+1

He puesto el código para onResume() {mediaplyer.resume()} etc. para onStop, onResume y onPause, pero no estoy seguro. Falla en mp.prepare(); – techtinkerer

+1

no se muestra nada cuando se activó la actividad. –

1

He utilizado este código para el juego de video en vista de la superficie

public class VideoPlayOnSurfaceView extends SurfaceView implements SurfaceHolder.Callback { 

    private MediaPlayer mediaPlayer; 
    private boolean has_started = false; 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    public VideoPlayOnSurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 
     init(); 
    } 

    public VideoPlayOnSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     init(); 
    } 

    public VideoPlayOnSurfaceView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    public VideoPlayOnSurfaceView(Context context) { 
     super(context); 
     init(); 
    } 

    private void init() { 
     mediaPlayer = new MediaPlayer(); 
     getHolder().addCallback(this); 
    } 

    @Override 
    public void surfaceCreated(SurfaceHolder holder) { 
     AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.small); 
     try { 
      if (!has_started) { 
       has_started = true; 
       mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength()); 
      } 

      mediaPlayer.prepare(); 
      android.view.ViewGroup.LayoutParams lp = getLayoutParams(); 
      lp.height = getHeight(); 
      lp.width = getWidth(); 

      setLayoutParams(lp); 
      mediaPlayer.setDisplay(holder); 
      mediaPlayer.setLooping(true); 
      mediaPlayer.start(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
    } 

    @Override public void surfaceDestroyed(SurfaceHolder holder) { 
     mediaPlayer.stop(); 
    } 
} 

archivo XML

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

     <YourPacakageName.VideoPlayOnSurfaceView 
      android:id="@+id/surface" 
      android:layout_width="fill_parent" 
      android:layout_height="match_parent" 
      android:paddingTop="10dip" /> 
</FrameLayout> 
Cuestiones relacionadas