Android将本地视频文件转换为一帧帧的JPEG NV21 I420格式的文件

这篇博客详细介绍了如何在Android平台上将本地视频文件逐帧解析为JPEG格式的图片,特别是NV21和I420这两种常见的YUV格式。内容包含具体的代码实现和步骤解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考地址

点击打开链接

github地址 点击打开链接 

代码注释为自己加入如下

package com.polarxiong.videotoimages;

import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.media.Image;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by zhantong on 16/5/12.
 */
public class VideoToFrames implements Runnable {
    private static final String TAG = "VideoToFrames";
    private static final boolean VERBOSE = false;
    private static final long DEFAULT_TIMEOUT_US = 10000;

    private static final int COLOR_FormatI420 = 1;
    private static final int COLOR_FormatNV21 = 2;


    private final int decodeColorFormat = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible;

    private LinkedBlockingQueue<byte[]> mQueue;
    private OutputImageFormat outputImageFormat;
    private String OUTPUT_DIR;
    private boolean stopDecode = false;

    private String videoFilePath;
    private Throwable throwable;
    private Thread childThread;

    private Callback callback;

    public interface Callback {
        void onFinishDecode();

        void onDecodeFrame(int index);
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public void setEnqueue(LinkedBlockingQueue<byte[]> queue) {
        mQueue = queue;
    }

    public void setSaveFrames(String dir, OutputImageFormat imageFormat) throws IOException {
        outputImageFormat = imageFormat;
        File theDir = new File(dir);
        if (!theDir.exists()) {
            theDir.mkdirs();
        } else if (!theDir.isDirectory()) {
            throw new IOException("Not a directory");
        }
        OUTPUT_DIR = theDir.getAbsolutePath() + "/";
    }

    public void stopDecode() {
        stopDecode = true;
    }

    public void decode(String videoFilePath) throws Throwable {
        this.videoFilePath = videoFilePath;
        if (childThread == null) {
            childThread = new Thread(this, "decode");
            childThread.start();
            if (throwable != null) {
                throw throwable;
            }
        }
    }

    public void run() {
        try {
            videoDecode(videoFilePath);
        } catch (Throwable t) {
            throwable = t;
        }
    }

    public void videoDecode(String videoFilePath) throws IOException {
        MediaExtractor extractor = null;
        MediaCodec decoder = null;
        try {
            //加载资源
            File videoFile = new File(videoFilePath);
            extractor = new MediaExtractor();
            extractor.setDataSource(videoFile.toString());
            //选择轨道号
            int trackIndex = selectTrack(extractor);
            if (trackIndex < 0) {
                throw new RuntimeException("No video track found in " + videoFilePath);
            }
            //选择读取视频数据
            extractor.selectTrack(trackIndex);
            MediaFormat mediaFormat = extractor.getTrackFormat(trackIndex);
            String mime = mediaFormat.getString(MediaFormat.KEY_MIME);
            //创建解码器
            decoder = MediaCodec.createDecoderByType(mime);
            showSupportedColorFormat(decoder.getCodecInfo().getCapabilitiesForType(mime));
            if (isColorFormatSupported(decodeColorFormat, decoder.getCodecInfo().getCapabilitiesForType(mime))) {
                mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, decodeColorFormat);
                Log.i(TAG, "set decode color format to type " + decodeColorFormat);
            } else {
                Log.i(TAG, "unable to set decode color format, color format type " + decodeColorFormat + " not supported");
            }
            //转换的方法
            decodeFramesToImage(decoder, extractor, mediaFormat);
            //关闭资源
            decoder.stop();
        } finally {
            //关闭资源释放资源
            if (decoder != null) {
                decoder.stop();
                decoder.release();
                decoder = null;
            }
            if (extractor != null) {
                extractor.release();
                extractor = null;
            }
        }
    }

    private void showSupportedColorFormat(MediaCodecInfo.CodecCapabilities caps) {
        System.out.print("supported color format: ");
        for (int c : caps.colorFormats) {
            System.out.print(c + "\t");
        }
        System.out.println();
    }

    private boolean isColorFormatSupported(int colorFormat, MediaCodecInfo.CodecCapabilities caps) {
        for (int c : caps.colorFormats) {
            if (c == colorFormat) {
                return true;
            }
        }
        return false;
    }

    private void decodeFramesToImage(MediaCodec decoder, MediaExtractor extractor, MediaFormat mediaFormat) {
        //解码详情
        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
        boolean sawInputEOS = false;
        boolean sawOutputEOS = false;
        //p配置解码格式
        decoder.configure(mediaFormat, null, null, 0);
        decoder.start();
        final int width = mediaFormat.getInteger(MediaFormat.KEY_WIDTH);
        final int height = mediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
        //帧数
        int outputFrameCount = 0;
        while (!sawOutputEOS && !stopDecode) {
            if (!sawInputEOS) {
                //开始加入缓冲区
                int inputBufferId = decoder.dequeueInputBuffer(DEFAULT_TIMEOUT_US);
                if (inputBufferId >= 0) {
                    ByteBuffer inputBuffer = decoder.getInputBuffer(inputBufferId);
                    //读取一帧数据
                    int sampleSize = extractor.readSampleData(inputBuffer, 0);
                    if (sampleSize < 0) {
                        decoder.queueInputBuffer(inputBufferId, 0, 0, 0L, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                        sawInputEOS = true;
                    } else {
                        long presentationTimeUs = extractor.getSampleTime();
                        decoder.queueInputBuffer(inputBufferId, 0, sampleSize, presentationTimeUs, 0);
                        //移动到下一帧
                        extractor.advance();
                    }
                }
            }
            //将缓冲区加入到解码区
            int outputBufferId = decoder.dequeueOutputBuffer(info, DEFAULT_TIMEOUT_US);
            if (outputBufferId >= 0) {
                //判断是否是最后一个flags标志
                if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                    sawOutputEOS = true;
                }
                boolean doRender = (info.size != 0);
                if (doRender) {
                    outputFrameCount++;
                    if (callback != null) {
                        //循环获取更新ui
                        callback.onDecodeFrame(outputFrameCount);
                    }
                    Image image = decoder.getOutputImage(outputBufferId);
                    //System.out.println("image format: " + image.getFormat());

                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] arr = new byte[buffer.remaining()];
                    buffer.get(arr);
                    if (mQueue != null) {
                        try {
                            mQueue.put(arr);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //判断图片格式并输出
                    if (outputImageFormat != null) {
                        String fileName;
                        switch (outputImageFormat) {
                            case I420:
                                fileName = OUTPUT_DIR + String.format("frame_%05d_I420_%dx%d.yuv", outputFrameCount, width, height);
                                dumpFile(fileName, getDataFromImage(image, COLOR_FormatI420));
                                break;
                            case NV21:
                                fileName = OUTPUT_DIR + String.format("frame_%05d_NV21_%dx%d.yuv", outputFrameCount, width, height);
                                dumpFile(fileName, getDataFromImage(image, COLOR_FormatNV21));
                                break;
                            case JPEG:
                                fileName = OUTPUT_DIR + String.format("frame_%05d.jpg", outputFrameCount);
                                compressToJpeg(fileName, image);
                                break;
                        }
                    }
                    //关闭并释放资源
                    image.close();
                    decoder.releaseOutputBuffer(outputBufferId, true);
                }
            }
        }
        if (callback != null) {
            callback.onFinishDecode();
        }
    }

    private static int selectTrack(MediaExtractor extractor) {
        int numTracks = extractor.getTrackCount();
        for (int i = 0; i < numTracks; i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("video/")) {
                if (VERBOSE) {
                    Log.d(TAG, "Extractor selected track " + i + " (" + mime + "): " + format);
                }
                return i;
            }
        }
        return -1;
    }

    private static boolean isImageFormatSupported(Image image) {
        int format = image.getFormat();
        switch (format) {
            case ImageFormat.YUV_420_888:
            case ImageFormat.NV21:
            case ImageFormat.YV12:
                return true;
        }
        return false;
    }

    private static byte[] getDataFromImage(Image image, int colorFormat) {
        if (colorFormat != COLOR_FormatI420 && colorFormat != COLOR_FormatNV21) {
            throw new IllegalArgumentException("only support COLOR_FormatI420 " + "and COLOR_FormatNV21");
        }
        if (!isImageFormatSupported(image)) {
            throw new RuntimeException("can't convert Image to byte array, format " + image.getFormat());
        }
        Rect crop = image.getCropRect();
        int format = image.getFormat();
        int width = crop.width();
        int height = crop.height();
        Image.Plane[] planes = image.getPlanes();
        byte[] data = new byte[width * height * ImageFormat.getBitsPerPixel(format) / 8];
        byte[] rowData = new byte[planes[0].getRowStride()];
        if (VERBOSE) Log.v(TAG, "get data from " + planes.length + " planes");
        int channelOffset = 0;
        int outputStride = 1;
        for (int i = 0; i < planes.length; i++) {
            switch (i) {
                case 0:
                    channelOffset = 0;
                    outputStride = 1;
                    break;
                case 1:
                    if (colorFormat == COLOR_FormatI420) {
                        channelOffset = width * height;
                        outputStride = 1;
                    } else if (colorFormat == COLOR_FormatNV21) {
                        channelOffset = width * height + 1;
                        outputStride = 2;
                    }
                    break;
                case 2:
                    if (colorFormat == COLOR_FormatI420) {
                        channelOffset = (int) (width * height * 1.25);
                        outputStride = 1;
                    } else if (colorFormat == COLOR_FormatNV21) {
                        channelOffset = width * height;
                        outputStride = 2;
                    }
                    break;
            }
            ByteBuffer buffer = planes[i].getBuffer();
            int rowStride = planes[i].getRowStride();
            int pixelStride = planes[i].getPixelStride();
            if (VERBOSE) {
                Log.v(TAG, "pixelStride " + pixelStride);
                Log.v(TAG, "rowStride " + rowStride);
                Log.v(TAG, "width " + width);
                Log.v(TAG, "height " + height);
                Log.v(TAG, "buffer size " + buffer.remaining());
            }
            int shift = (i == 0) ? 0 : 1;
            int w = width >> shift;
            int h = height >> shift;
            buffer.position(rowStride * (crop.top >> shift) + pixelStride * (crop.left >> shift));
            for (int row = 0; row < h; row++) {
                int length;
                if (pixelStride == 1 && outputStride == 1) {
                    length = w;
                    buffer.get(data, channelOffset, length);
                    channelOffset += length;
                } else {
                    length = (w - 1) * pixelStride + 1;
                    buffer.get(rowData, 0, length);
                    for (int col = 0; col < w; col++) {
                        data[channelOffset] = rowData[col * pixelStride];
                        channelOffset += outputStride;
                    }
                }
                if (row < h - 1) {
                    buffer.position(buffer.position() + rowStride - length);
                }
            }
            if (VERBOSE) Log.v(TAG, "Finished reading data from plane " + i);
        }
        return data;
    }

    private static void dumpFile(String fileName, byte[] data) {
        FileOutputStream outStream;
        try {
            outStream = new FileOutputStream(fileName);
        } catch (IOException ioe) {
            throw new RuntimeException("Unable to create output file " + fileName, ioe);
        }
        try {
            outStream.write(data);
            outStream.close();
        } catch (IOException ioe) {
            throw new RuntimeException("failed writing data to file " + fileName, ioe);
        }
    }

    private void compressToJpeg(String fileName, Image image) {
        FileOutputStream outStream;
        try {
            outStream = new FileOutputStream(fileName);
        } catch (IOException ioe) {
            throw new RuntimeException("Unable to create output file " + fileName, ioe);
        }
        Rect rect = image.getCropRect();
        YuvImage yuvImage = new YuvImage(getDataFromImage(image, COLOR_FormatNV21), ImageFormat.NV21, rect.width(), rect.height(), null);
        yuvImage.compressToJpeg(rect, 100, outStream);
    }
}

<think>我们正在讨论的是在Android平台上将MP4文件转换为YUV格式。YUV是一种原始的视频像素格式,常用于视频处理和分析。在Android中,我们可以使用FFmpeg库来实现这一功能,因为FFmpeg是一个强大的多媒体处理框架,支持多种格式的解码和转换。 根据引用[2]和引用[3],我们可以得知使用FFmpeg将视频转换为YUV格式的一般步骤: 1. 注册FFmpeg组件(av_register_all,但新版本中可能不需要显式调用)。 2. 打开输入文件(avformat_open_input)获取AVFormatContext。 3. 查找流信息(avformat_find_stream_info)。 4. 找到视频流,并获取对应的解码器上下文(AVCodecContext)。 5. 根据解码器上下文找到合适的解码器(avcodec_find_decoder)。 6. 打开解码器(avcodec_open2)。 7. 循环读取视频(av_read_frame),得到AVPacket。 8. 将AVPacket发送给解码器(avcodec_send_packet),然后接收解码后的AVFrame(avcodec_receive_frame)。 9. 将解码后的(通常是RGB或YUV格式,但可能不是我们想要的特定YUV格式)通过sws_scale转换为目标YUV格式(如YUV420P)。 10. 将转换后的YUV数据写入文件。 在Android中,我们可以通过编译FFmpeg为Android可用的库(如.so文件),然后使用JNI调用FFmpeg的API来实现。 另外,引用[1]提供了一种在Android上将YUV数据(NV21格式)压缩为JPEG的方法,但这并不是我们当前需要的。不过,它展示了Android中处理YUV数据的一种方式。 因此,针对用户的问题“Android如何将MP4文件转换为YUV格式”,我们可以提供两种方法: 方法1:使用FFmpeg命令行工具 在Android应用中集成FFmpeg可执行文件,然后通过执行命令将MP4转换为YUV。例如,命令如下: ```bash ffmpeg -i input.mp4 -c:v rawvideo -pix_fmt yuv420p output.yuv ``` 但是,在Android中执行命令需要获取root权限或者将FFmpeg可执行文件打包到应用中,并通过Runtime.getRuntime().exec()来执行。 方法2:使用FFmpeg库进行编程 通过JNI调用FFmpeg库,编写C/C++代码来实现解码和转换。步骤如上所述。 下面,我们将重点介绍方法2的编程实现步骤(在Android中使用FFmpeg库): ### 步骤1:准备FFmpeg库 首先,需要为Android编译FFmpeg库(生成.so文件)。可以参考网上的教程,或者使用已经编译好的库。将编译好的库(例如libavcodec.so, libavformat.so, libavutil.so, libswscale.so等)放入Android项目的jniLibs目录中。 ### 步骤2:创建JNI接口 在Java层,我们创建一个本地方法,用于将MP4文件转换为YUV文件。 ```java public class VideoDecoder { static { System.loadLibrary("avcodec"); System.loadLibrary("avformat"); System.loadLibrary("avutil"); System.loadLibrary("swscale"); System.loadLibrary("myffmpeg"); // 我们自己编写的JNI库 } public native int convertToYuv(String inputPath, String outputPath); } ``` ### 步骤3:编写JNI代码 在JNI中,我们实现convertToYuv函数,使用FFmpeg进行解码和转换。 以下是一个简化的JNI代码示例(实际开发中需要处理错误和资源释放): ```c #include <jni.h> #include <android/log.h> #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> #define LOG_TAG "FFmpegDecoder" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) JNIEXPORT jint JNICALL Java_com_example_VideoDecoder_convertToYuv(JNIEnv *env, jobject instance, jstring inputPath_, jstring outputPath_) { const char *inputPath = (*env)->GetStringUTFChars(env, inputPath_, 0); const char *outputPath = (*env)->GetStringUTFChars(env, outputPath_, 0); AVFormatContext *fmt_ctx = NULL; AVCodecContext *codec_ctx = NULL; AVFrame *frame = NULL, *frame_yuv = NULL; AVPacket pkt; int video_stream_index = -1; const AVCodec *codec = NULL; int ret; FILE *outfile = NULL; struct SwsContext *sws_ctx = NULL; // 打开输入文件 if ((ret = avformat_open_input(&fmt_ctx, inputPath, NULL, NULL)) < 0) { LOGE("Could not open input file."); goto end; } if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) { LOGE("Failed to get input stream information."); goto end; } // 找到视频流 for (int i = 0; i < fmt_ctx->nb_streams; i++) { if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { video_stream_index = i; break; } } if (video_stream_index == -1) { LOGE("No video stream found."); goto end; } // 获取解码器 codec = avcodec_find_decoder(fmt_ctx->streams[video_stream_index]->codecpar->codec_id); if (!codec) { LOGE("Codec not found."); goto end; } codec_ctx = avcodec_alloc_context3(codec); if (!codec_ctx) { LOGE("Could not allocate codec context."); goto end; } if ((ret = avcodec_parameters_to_context(codec_ctx, fmt_ctx->streams[video_stream_index]->codecpar)) < 0) { LOGE("Failed to copy codec parameters to codec context."); goto end; } if ((ret = avcodec_open2(codec_ctx, codec, NULL)) < 0) { LOGE("Failed to open codec."); goto end; } // 打开输出文件 outfile = fopen(outputPath, "wb"); if (!outfile) { LOGE("Could not open output file."); goto end; } frame = av_frame_alloc(); frame_yuv = av_frame_alloc(); if (!frame || !frame_yuv) { LOGE("Could not allocate frames."); goto end; } // 设置frame_yuv的格式为YUV420P,并分配缓冲区 int width = codec_ctx->width; int height = codec_ctx->height; frame_yuv->format = AV_PIX_FMT_YUV420P; frame_yuv->width = width; frame_yuv->height = height; ret = av_frame_get_buffer(frame_yuv, 0); if (ret < 0) { LOGE("Could not allocate frame buffer."); goto end; } // 初始化SWS上下文用于格式转换转换为YUV420P) sws_ctx = sws_getContext(width, height, codec_ctx->pix_fmt, width, height, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); if (!sws_ctx) { LOGE("Could not create scale context."); goto end; } av_init_packet(&pkt); pkt.data = NULL; pkt.size = 0; // 读取并解码 while (av_read_frame(fmt_ctx, &pkt) >= 0) { if (pkt.stream_index == video_stream_index) { ret = avcodec_send_packet(codec_ctx, &pkt); if (ret < 0) { LOGE("Error sending packet for decoding."); continue; } while (ret >= 0) { ret = avcodec_receive_frame(codec_ctx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { break; } else if (ret < 0) { LOGE("Error during decoding."); break; } // 转换到YUV420P sws_scale(sws_ctx, (const uint8_t *const *)frame->data, frame->linesize, 0, height, frame_yuv->data, frame_yuv->linesize); // 将YUV数据写入文件 // YUV420P格式:先写Y平面,再写U平面,再写V平面 // 每个平面大小为 width * height (Y), width/2 * height/2 (U), width/2 * height/2 (V) for (int i = 0; i < height; i++) { fwrite(frame_yuv->data[0] + i * frame_yuv->linesize[0], 1, width, outfile); } for (int i = 0; i < height / 2; i++) { fwrite(frame_yuv->data[1] + i * frame_yuv->linesize[1], 1, width / 2, outfile); } for (int i = 0; i < height / 2; i++) { fwrite(frame_yuv->data[2] + i * frame_yuv->linesize[2], 1, width / 2, outfile); } } } av_packet_unref(&pkt); } // 刷新解码器 pkt.data = NULL; pkt.size = 0; avcodec_send_packet(codec_ctx, &pkt); end: // 释放资源 if (outfile) fclose(outfile); if (sws_ctx) sws_freeContext(sws_ctx); if (frame) av_frame_free(&frame); if (frame_yuv) av_frame_free(&frame_yuv); if (codec_ctx) avcodec_free_context(&codec_ctx); if (fmt_ctx) avformat_close_input(&fmt_ctx); (*env)->ReleaseStringUTFChars(env, inputPath_, inputPath); (*env)->ReleaseStringUTFChars(env, outputPath_, outputPath); return ret < 0 ? -1 : 0; } ``` ### 步骤4:在Android应用中调用 在Android应用中,我们可以这样调用: ```java VideoDecoder decoder = new VideoDecoder(); decoder.convertToYuv(inputMp4Path, outputYuvPath); ``` ### 注意事项 1. 由于视频文件可能很大,转换过程可能耗时,应该在后台线程执行。 2. 需要确保有足够的存储空间来保存YUV文件(因为YUV文件通常比原始视频大很多)。 3. 上述代码是简化版本,实际应用中需要更详细的错误处理和资源释放。 另外,引用[3]提供了一个完整的项目,可以参考其实现:https://github.com/979451341/Audio-and-video-learning-materials/tree/master/FFmpeg(MP4转yuv) 综上所述,在Android上将MP4转换为YUV格式可以通过FFmpeg库编程实现,或者使用FFmpeg命令行工具。编程实现更加灵活,但需要一定的FFmpeg知识和JNI编程经验。 --- §§相关问题§§ 1. 如何为Android编译FFmpeg? 2. 在Android中使用FFmpeg库时,如何管理内存以避免OOM? 3. YUV420P格式的数据布局是怎样的? 4. 如何将转换后的YUV数据实时显示在Android的Surface上?</think>在 Android 平台上将 MP4 文件转换为 YUV 格式,可以通过 FFmpeg 库实现。以下是两种主要方法及其实现步骤: ### 方法一:使用 FFmpeg 命令行工具(推荐) 1. **集成 FFmpeg 到 Android 项目** - 下载编译好的 [Android FFmpeg 库](https://github.com/FFmpeg/FFmpeg) - 将 `ffmpeg` 可执行文件放入 `app/src/main/assets` 目录 - 在运行时复制到应用目录: ```java public void copyFFmpeg(Context context) { try { InputStream in = context.getAssets().open("ffmpeg"); File outFile = new File(context.getFilesDir(), "ffmpeg"); FileOutputStream out = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.close(); in.close(); // 设置可执行权限 Runtime.getRuntime().exec("chmod 700 " + outFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } ``` 2. **执行转换命令** ```java public void convertMp4ToYuv(String inputPath, String outputPath) { try { File ffmpeg = new File(getFilesDir(), "ffmpeg"); String cmd = ffmpeg.getAbsolutePath() + " -i " + inputPath + " -c:v rawvideo -pix_fmt yuv420p " + outputPath; Process process = Runtime.getRuntime().exec(cmd); int exitCode = process.waitFor(); if (exitCode == 0) { Log.d("FFmpeg", "转换成功"); } } catch (Exception e) { e.printStackTrace(); } } ``` ### 方法二:使用 FFmpeg 库编程实现 1. **添加依赖** 在 `build.gradle` 中添加: ```gradle implementation 'com.arthenica:mobile-ffmpeg-full:4.4' ``` 2. **解码 MP4 并输出 YUV** ```java import com.arthenica.mobileffmpeg.FFmpeg; public void convertToYuv(String inputPath, String outputPath) { String cmd = "-i " + inputPath + " -c:v rawvideo -pix_fmt yuv420p " + outputPath; int result = FFmpeg.execute(cmd); if (result == 0) { Log.d("FFmpeg", "转换成功"); } } ``` ### 关键参数说明 - `-c:v rawvideo`:指定输出原始视频流 - `-pix_fmt yuv420p`:指定输出格式为 YUV420P(最常用的 YUV 格式) - 输出文件扩展名建议使用 `.yuv` ### 注意事项 1. **权限申请**:需要 `READ_EXTERNAL_STORAGE` 权限访问输入文件 2. **大文件处理**:YUV 文件通常很大(1分钟 720p 视频 ≈ 200MB),建议: - 在后台线程处理 - 提供进度提示 - 确保足够存储空间 3. **格式验证**:使用 [YUV Player](http://www.yuvplayer.com/) 可验证输出文件 ### 完整示例项目 参考 GitHub 上的实现: [FFmpeg MP4 转 YUV 示例](https://github.com/979451341/Audio-and-video-learning-materials/tree/master/FFmpeg(MP4转yuv))[^3] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值