您的位置:首页 > 其它

安卓MediaPlayer和VideoView简单使用

2016-09-22 18:27 218 查看
开发过程当中,难免会遇到需要用播放器的地方,下面就来说下安卓系统自带的MediaPlayer和VideoView。
思路:
MediaPlayer
首先创建一个MediaPlayer对象,然后调用setDataSource()方法来设置音频文件的路径,再调用prepare()方法让MediaPlayer进入准备状态,接下来调用start()开始播放,pause()暂停,reset()停止播放。release()释放掉相关资源,seekTo()从指定位置开始播放等等。
用法和举例:
声明变量 private MediaPlayer mMediaPlayer=new MediaPlayer();
在Activity的初始化方法里面写上初始化方法

public void initVideoPath() {
try{
File file = new File(Environment.getExternalStorageDirectory(), "文件名字带后缀的");
mMediaPlayer.setDataSource(file.getPath());
mMediaPlayer.prepare();
}catch (Exception e){
e.printStackTrace();
}

public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_paly:
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
break;
case R.id.tv_pause:
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
break;
case R.id.tv_replay:
if (mMediaPlayer.isPlaying()) {
initVideoPath();
}
break;
}
@Override
protected void onPause() {
super.onPause();
if (null!=mMediaPlayer){
mMediaPlayer.stop();
mMediaPlayer.release();
}
}

VideoView
方法差不多,setVideoPath()设置播放的视频文件位置,start()开始或者继续播放,pause()暂停播放,reseum()将视频从头开始播放,seekto()从指定位置开始播放视频,isPlaying()判断当前是否正在播放视频
用法和举例:
用之前要在布局文件里面写上该控件。
<VideoView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="100"/>
在Activity的初始化方法里面写上初始化方法
public void initVideoPath(){
File file=new File(Environment.getExternalStorageDirectory(),"文件名字带后缀的");
videoView.setVideoPath(file.getPath());

}
在写个点击事件
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_paly:
if (!videoView.isPlaying()) {
videoView.start();
}
break;
case R.id.tv_pause:
if (videoView.isPlaying()) {
videoView.pause();
}
break;
case R.id.tv_replay:
if (videoView.isPlaying()) {
videoView.resume();
}
break;
}
}
记得要在页面销毁的时候把资源释放掉
protected void onDestory() {
super.onPause();
if (null!=videoView){
videoView.suspend();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: