2012-01-12 12 views
35

Ho bisogno di usare il video come sfondo. Per prima cosa ho inserito il file video in una cartella disegnabile e chiamato come sfondo di LinearLayout in main.xml. Ma durante l'esecuzione dell'app, ho visto solo uno schermo nero. Poi ho provato ad usare VideoView e lo ha chiamato come segue:Integrazione del file video nell'app per Android come sfondo dell'app

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

Nel mio file di attività ho chiamato con il seguente frammento di codice:

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

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

Ma ancora non ricevo il file video lì. La mia proposta principale è quella di utilizzare un video a bolle come sfondo e di mettere due pulsanti a forma di bolla su di esso e dare all'utente una sensazione come schermo di visualizzazione dell'acqua. Qualcuno può aiutarmi?

Anche il file video che desidero utilizzare dalla cartella res. Non dalla scheda SD o da qualsiasi cartella multimediale esterna.

risposta

39

Bene amico mio, prima di tutto non è possibile impostare uno sfondo per il tuo VideoView e farlo giocare sullo sfondo del tuo schermo.

Per favore segui i miei passi e aggiungi il tuo impegno e dovresti essere lì.

Rimuovere il video dalla cartella drawable e aggiungerlo alla cartella raw. Per favore google come creare una cartella raw. È semplice però. E metti il ​​tuo file video al suo interno.

Prima di tutto, crea un SurfaceView nel tuo xml come questo.

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

Ora, creare una classe come quella qui sotto, che può implementare 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); 
     //... 
    } 
} 

Ora la tua classe vi chiederà per i metodi non implementati da aggiungere. Aggiungere questi metodi semplicemente cliccando su "Aggiungi metodi non implementati"

Ora sarete in grado di vedere un metodo generato automaticamente come questo,

@Override 
public void surfaceCreated(SurfaceHolder holder) { 

} 

E dentro questo metodo, aggiungere il codice qui sotto,

@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

Esiste un modo ho potuto fare lo stesso da un servizio in background? Come creare un video player dal servizio? –

+0

Che dire di 'TextureView'? @AndroSelva –

+3

Questo non funziona per me, Spero che qualcuno abbia una soluzione migliore o un modo efficace per integrare un file video. – XcodeNOOB

0

ho usato

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

invece di

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

e utilizzato il codice seguente per il lettore multimediale di installazione.

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 sul tuo XML e mettere il video in raw/intro.mp4

+0

È necessario chiudere. infine { try { afd.close(); } catch (IOException e) { e.printStackTrace(); } } –

6

La versione completa della versione modificata di luigi23 ad evitare alcuni crash.

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); 
    } 
} 

nulla sull'attività principale. si potrebbe desiderare di renderlo fullscreen aggiungendo

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

Creare un file 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(); 
    } 
} 

aggiungere un "slideshow.mp4" di risorse/prime

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

Alcune note.

Aggiunta di un video renderà il vostro apk enorme quindi si potrebbe voler evitare questo ... Di tanto in tanto si blocca sconosciuti si verificano anche su telefoni di fascia alta (Galaxy S6) E 'essenziale per mantenere il file di piccole dimensioni.

+2

Questo codice funziona quando l'attività viene creata e in esecuzione. Ma quando andiamo alla prossima attività e torniamo a questo, fallisce con errore come: java.lang.IllegalStateException su android.media.MediaPlayer._prepare (metodo nativo) su android.media.MediaPlayer.prepare (MediaPlayer.java:1135) a – techtinkerer

+1

Ho inserito il codice per onResume() {mediaplyer.resume()} ecc. Per onStop, onResume e onPause ma non sono sicuro. Fallisce su mp.prepare(); – techtinkerer

+1

non viene mostrato nulla quando l'attività è stata arrestata. –

1

Ho usato questo codice per il video gioco sulla superficie vista

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(); 
    } 
} 

file 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> 
Problemi correlati