使用SurfaceView和MediaPlayer實現視頻做為背景,surfaceview背景透明
情境:像我們在Uber應用開場,看到一一段視頻作為開始,這樣子讓使用者很快投入應用使用的情境中去,這種以視頻作為開場的應用,我們是不是覺得很高大上呢,哈哈,其實是使用了SerfaceView去載入一段小視頻,然後使用mediaplayer進行播放,然後迴圈。
先吧。
這裡我貼出主要代碼的實現
import java.io.IOException;import android.app.Activity;import android.content.Intent;import android.content.res.AssetFileDescriptor;import android.media.AudioManager;import android.media.MediaPlayer;import android.media.MediaPlayer.OnPreparedListener;import android.os.Bundle;import android.view.SurfaceHolder;import android.view.SurfaceView;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private SurfaceView surfaceview;private Button btnGo;private MediaPlayer mediaPlayer;private int postion = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById();initView();}protected void findViewById() {// TODO Auto-generated method stubsurfaceview = (SurfaceView) findViewById(R.id.surfaceView);btnGo = (Button) findViewById(R.id.btn_goto);}protected void initView() {// TODO Auto-generated method stubmediaPlayer = new MediaPlayer();surfaceview.getHolder().setKeepScreenOn(true);surfaceview.getHolder().addCallback(new SurfaceViewLis());btnGo.setOnClickListener(this);}private class SurfaceViewLis implements SurfaceHolder.Callback {@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {}@Overridepublic void surfaceCreated(SurfaceHolder holder) {if (postion == 0) {try {play();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {}}public void play() throws IllegalArgumentException, SecurityException,IllegalStateException, IOException {mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);AssetFileDescriptor fd = this.getAssets().openFd("start.mp4");mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(),fd.getLength());mediaPlayer.setLooping(true);mediaPlayer.setDisplay(surfaceview.getHolder());// 通過非同步方式裝載媒體資源mediaPlayer.prepareAsync();mediaPlayer.setOnPreparedListener(new OnPreparedListener() {@Overridepublic void onPrepared(MediaPlayer mp) {// 裝載完畢回調mediaPlayer.start();}});}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btn_goto:startActivity(new Intent(this, OtherActivity.class));finish();break;default:break;}}}
完整的demo請到我的github項目首頁進行下載
https://github.com/paulzeng/surfaceviewbackground
點擊開啟連結
期待大家一起follow,加入更酷的效果!
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。