标签:android mediaplayer 视频
前面介绍了使用VideoView播放视频,使用VideoView播放视频简单方便,但是习惯使用MediaPlayer的开发者还是使用MediaPlayer;MediaPlayer本身主要用于播放音频,没有提供视频输出画面,需要借助SurfaceView,VideoView是其子类;
播放视频步骤:
【1】布局文件加入SurfaceView
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
【3】创建MediaPlayer对象,加载视频文件
player.setDataSource(Environment.getExternalStorageDirectory() + "/20150915_160202.mp4");
【4】得到SurfaceHolder添加监听器
SurfaceHolder surfaceHolder=mSurfaceView.getHolder();
surfaceHolder.setKeepScreenOn(true);
【5】调用MediaPlayer的setDisplay(SurfaceHolder sh)
player.setDisplay(surfaceHolder);//设置视频播放位置
【6】start()、stop()、pause()
下面为程序源码
public class MainActivity extends Activity {
private SurfaceView mSurfaceView;
private Button mButton;
private MediaPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (player == null) {
player = new MediaPlayer();
}
player.reset();
try {
player.setDataSource(Environment.getExternalStorageDirectory() + "/20150915_160202.mp4");
player.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置播放声音类型
SurfaceHolder surfaceHolder=mSurfaceView.getHolder();
surfaceHolder.setKeepScreenOn(true);
player.setDisplay(surfaceHolder);//设置视频播放位置
player.prepare();//准备
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();//开始播放
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:android mediaplayer 视频
原文地址:http://blog.csdn.net/taoolee/article/details/49360221