本小记继续上一篇的代码
主要实现功能为:对编码器编译压缩后输出的视频流用MediaMuxer封装到MP4容器。
//采用线程进行录屏的耗时操作
public class VideoThread extends Thread {
private Context mContext;
private static final String MIME_TYPE = "video/avc";
private VirtualDisplay virtualDisplay;
private MediaProjection projection;
private AtomicBoolean mQuit = new AtomicBoolean(false);
private int videoWidth;
private int videoHeight;
private Handler handler = null;
//构造函数,传入上下文和屏幕大小
public VideoThread(Context context, int width, int height){
mContext = context;
videoWidth = width;
videoHeight = height;
}
public final void quit(){
mQuit.set(true);
}
@Override
public void run(){
Surface surface = null;
MediaMuxer mediaMuxer = null; //MediaMuxer的使用要按照Constructor -> addTrack -> start -> writeSampleData -> stop 的顺序
MediaCodec mediaCodec = null;
//获取文件保存路径
long timeMillis = System.currentTimeMillis();
Date date = new Date(timeMillis);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
String path = "ScreenShot" + simpleDateFormat.format(date) + ".mp4";
File file = new File(Environment.getExternalStorageDirectory(), path);
File parentFile = file.getParentFile();
if (parentFile == null || !parentFile.exists()) {
parentFile.mkdir();
}
//初始化编码器、创建MediaFormat设置Media格式
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, videoWidth, videoHeight);
f