Android中常用的视频格式
- MP4:分辨率高、大小适中。
- 3GP:体积小、移动性强。
使用步骤
代码实现
MyVideoView.java
package com.lzp.videoview;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;
public class MyVideoView extends VideoView {
public MyVideoView(Context context) {
super(context);
}
public MyVideoView(Context context, AttributeSet attrs){
super(context,attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//为了让视频全屏显示所有要重写该方法
int width = getDefaultSize(0, widthMeasureSpec);
int height = getDefaultSize(0, heightMeasureSpec);
setMeasuredDimension(width, height);
}
}
MainActivity.java
package com.lzp.videoview;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.WindowManager;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
MyVideoView videoView = findViewById(R.id.video);//获取VideoView组件
/****加载要播放的视频****/
File file = new File(Environment.getExternalStorageDirectory()
+"/80stest.mp4");//获取文件对象
if(file.exists()){
videoView.setVideoPath(file.getAbsolutePath());
//指定要播放的视频
}else{
Toast.makeText(MainActivity.this,
"没有该视频资源",Toast.LENGTH_SHORT).show();
}
/***控制视频的播放****/
android.widget.MediaController mc = new android.
widget.MediaController
(MainActivity.this);//创建MediaController
videoView.setMediaController(mc);
//让VideoView和MediaController关联
videoView.requestFocus();//让VideoView获得焦点
videoView.start();//开始播放视频
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(MainActivity.this,"视频播放完毕",Toast.LENGTH_SHORT).show();
}
});
}
}
效果:
项目地址:
https://gitee.com/peterLiz/android_learning.git
技术支持请加QQ:599490685