package com.ning.sufaceview; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class videoActivity extends AppCompatActivity implements View.OnClickListener { private Button buttnplay; private MyvideoSurfaceview video_surface; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); initView(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); } private void initView() { buttnplay = (Button) findViewById(R.id.buttnplay); video_surface = (MyvideoSurfaceview) findViewById(R.id.video_surface); buttnplay.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.buttnplay: play(); break; } } private void play() { String path = Environment.getDownloadCacheDirectory().getPath();// 外部存储根路径+ video_surface.playVoider(path); } }
//还需要一个调用方法以及外部权限
package com.ning.sufaceview; import android.content.Context; import android.media.MediaPlayer; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.io.IOException; /** * Created by 行歌 on 2017/11/17. */ public class MyvideoSurfaceview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder holder; private MediaPlayer mMediaPlayer; public MyvideoSurfaceview(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { holder = getHolder(); holder.addCallback(this); } public void playVoider(String pash){ if(mMediaPlayer==null){ mMediaPlayer=new MediaPlayer(); //设置播放源 try { mMediaPlayer.setDataSource(pash); mMediaPlayer.setDisplay(holder); mMediaPlayer.prepare(); mMediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void surfaceCreated(SurfaceHolder holder) { } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { mMediaPlayer.reset(); mMediaPlayer=null; } }