安卓MediaPlayer和VideoView简单使用

开发过程当中,难免会遇到需要用播放器的地方,下面就来说下安卓系统自带的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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值