当前位置: 首页 > news >正文

Android 使用MediaMuxer+MediaCodec编码MP4视频

以下是一个基于 MediaMuxer + MediaCodec 的 YUV420 转 MP4 工具类实现,支持开始录制、送帧、结束录制接口:

import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.util.Log;
import java.io.IOException;
import java.nio.ByteBuffer;public class YuvToMp4Encoder {private static final String TAG = "YuvToMp4Encoder";private static final String MIME_TYPE = "video/avc"; // H.264编码private static final int TIMEOUT_USEC = 10000; // 10ms超时// 编码器状态public enum EncoderState {IDLE, PREPARED, ENCODING, STOPPED}private MediaCodec mMediaCodec;private MediaMuxer mMediaMuxer;private int mTrackIndex;private boolean mMuxerStarted;private EncoderState mState = EncoderState.IDLE;private int mWidth;private int mHeight;private int mFrameRate;private int mBitRate;private long mPresentationTimeUs;private long mFirstFrameTime = -1;/*** 初始化编码器* @param width 视频宽度* @param height 视频高度* @param frameRate 帧率* @param bitRate 比特率 (bps)*/public YuvToMp4Encoder(int width, int height, int frameRate, int bitRate) {this.mWidth = width;this.mHeight = height;this.mFrameRate = frameRate;this.mBitRate = bitRate;}/*** 准备编码器* @param outputPath 输出文件路径* @throws IOException 初始化异常*/public void prepare(String outputPath) throws IOException {if (mState != EncoderState.IDLE) {throw new IllegalStateException("Encoder must be in IDLE state");}try {// 1. 创建并配置MediaCodecmMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);format.setInteger(MediaFormat.KEY_BIT_RATE, mBitRate);format.setInteger(MediaFormat.KEY_FRAME_RATE, mFrameRate);format.setInteger(MediaFormat.KEY_COLOR_FORMAT,MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar);format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); // 关键帧间隔(秒)mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);mMediaCodec.start();// 2. 创建MediaMuxermMediaMuxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);mTrackIndex = -1;mMuxerStarted = false;mState = EncoderState.PREPARED;mPresentationTimeUs = 0;Log.i(TAG, "Encoder prepared successfully");} catch (Exception e) {e.printStackTrace();release();}}/*** 开始编码*/public void start() {if (mState != EncoderState.PREPARED) {throw new IllegalStateException("Encoder must be prepared before starting");}mState = EncoderState.ENCODING;mFirstFrameTime = -1;Log.i(TAG, "Encoder started");}/*** 输入一帧YUV420数据* @param yuvData YUV420字节数组* @param timestamp 时间戳(ns)*/public void feedFrame(byte[] yuvData, long timestamp) {if (mState != EncoderState.ENCODING) {Log.w(TAG, "Ignoring frame - encoder not in encoding state");return;}try {// 1. 获取输入缓冲区int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);if (inputBufferIndex < 0) {Log.w(TAG, "No available input buffer, skipping frame");return;}// 2. 填充YUV数据ByteBuffer inputBuffer = mMediaCodec.getInputBuffer(inputBufferIndex);if (inputBuffer != null) {inputBuffer.clear();inputBuffer.put(yuvData);// 3. 计算PTS (呈现时间戳)long presentationTimeUs = timestamp / 1000; // ns -> μsif (mFirstFrameTime < 0) {mFirstFrameTime = presentationTimeUs;}presentationTimeUs -= mFirstFrameTime;// 4. 提交到编码器mMediaCodec.queueInputBuffer(inputBufferIndex,0,yuvData.length,presentationTimeUs,0);}// 5. 处理编码输出drainEncoder(false);} catch (Exception e) {e.printStackTrace();}}/*** 停止编码并释放资源*/public void stop() {if (mState == EncoderState.STOPPED || mState == EncoderState.IDLE) {return;}try {if (mState == EncoderState.ENCODING) {// 发送结束信号drainEncoder(true);// 停止编码器if (mMediaCodec != null) {mMediaCodec.stop();}}// 停止混合器if (mMediaMuxer != null && mMuxerStarted) {mMediaMuxer.stop();}Log.i(TAG, "Encoder stopped successfully");} catch (Exception e) {e.printStackTrace();} finally {release();mState = EncoderState.STOPPED;}}// 释放所有资源private void release() {try {if (mMediaCodec != null) {mMediaCodec.release();mMediaCodec = null;}if (mMediaMuxer != null) {mMediaMuxer.release();mMediaMuxer = null;}} catch (Exception e) {e.printStackTrace();}mMuxerStarted = false;mTrackIndex = -1;}// 处理编码器输出private void drainEncoder(boolean endOfStream) {if (endOfStream) {// 发送结束信号int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);if (inputBufferIndex >= 0) {mMediaCodec.queueInputBuffer(inputBufferIndex, 0, 0, 0,MediaCodec.BUFFER_FLAG_END_OF_STREAM);}}// 处理所有可用输出while (true) {MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, TIMEOUT_USEC);if (outputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {if (!endOfStream) break;} else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {// 格式改变时设置混合器if (mMuxerStarted) {throw new RuntimeException("Format changed after muxer started");}MediaFormat newFormat = mMediaCodec.getOutputFormat();mTrackIndex = mMediaMuxer.addTrack(newFormat);mMediaMuxer.start();mMuxerStarted = true;} else if (outputBufferIndex < 0) {
//                Log.w(TAG, "Unexpected result from dequeueOutputBuffer: " + outputBufferIndex);} else {ByteBuffer outputBuffer = mMediaCodec.getOutputBuffer(outputBufferIndex);if (outputBuffer == null) {Log.e(TAG, "Output buffer was null");} else {// 写入混合器if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0 && bufferInfo.size > 0) {if (mMuxerStarted) {outputBuffer.position(bufferInfo.offset);outputBuffer.limit(bufferInfo.offset + bufferInfo.size);mMediaMuxer.writeSampleData(mTrackIndex, outputBuffer, bufferInfo);}}// 检查结束标志if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {break;}}mMediaCodec.releaseOutputBuffer(outputBufferIndex, false);}}}/*** 获取当前编码器状态*/public EncoderState getState() {return mState;}
}
http://www.dtcms.com/a/355419.html

相关文章:

  • 把 AI 塞进「智能手环」——基于心率变异的零样本压力监测手环
  • sqlserver: count(*)
  • TCP和HTTP的keep-alive的区别
  • 嵌入式第四十天(TCP并发服务端(IO多路复用))
  • 【Python 入门】(1)Python 语言基础(语法特点)
  • OSI模型和TCP/IP模型区别是什么
  • JAVA全栈Redis篇————Redis常用数据类型概述
  • 如何快速copy复制一个网站,或是将网站本地静态化访问
  • 电力电子中的变压器原理、作用、选型与测量指南-超简单解读
  • 雷达传感器和红外传感器的区别
  • MCP tutorials
  • HOOPS Communicator 2025.6.0更新发布:WebViewer UI全面进化,BIM支持再升级
  • C++(Qt)软件调试---vspkg安装crashpad(34)
  • 浅谈 Java 中的 import static 使用方式
  • Docker 是什么?
  • RabbitMQ-高级特性
  • 机器视觉学习-day09-图像矫正
  • 客户预充值系统(一) - 数据库设计与数据插入
  • JVM——八股文
  • curl、python-requests、postman和jmeter的对应关系
  • DJI无人机云哨DroneID技术解析:天空中的数字身份证
  • 2025年KBS SCI1区TOP,矩阵差分进化算法+移动网络视觉覆盖无人机轨迹优化,深度解析+性能实测
  • Maven核心用法
  • ubuntu挂载外接硬盘
  • IDEA 中创建 Springboot 项目没有 Java8 选项的解决办法
  • 介绍智慧城管十大核心功能之一:风险预警系统
  • 关于npm安装electron和better-sqlite3失败问题
  • Copilot、Cursor、Trae、ChatGPT 的“四件套”场景选择表
  • 第六届智能计算与人机交互国际研讨会(ICHCI 2025)
  • MySQL 与 ClickHouse 深度对比:架构、性能与场景选择指南