1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| 一、概念 在 Android 中使用 FFmpeg 解码音视频,通常通过 JNI 调用 FFmpeg C/C++ 库实现,流程如下:
二、FFmpeg 解码音视频的简要流程 2.1 初始化 FFmpeg av_register_all(); // 已废弃但仍常见,建议使用 avformat_network_init()
2.2 打开输入文件或流 avformat_open_input(&fmt_ctx, inputPath, NULL, NULL); avformat_find_stream_info(fmt_ctx, NULL);
2.3 查找音视频流索引 video_stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, ...);
2.4 打开解码器 AVCodec *codec = avcodec_find_decoder(codecpar->codec_id); avcodec_open2(codec_ctx, codec, NULL);
2.5 读取并解码数据 while (av_read_frame(fmt_ctx, &pkt) >= 0) { if (pkt.stream_index == video_stream_index) { avcodec_send_packet(codec_ctx, &pkt); while (avcodec_receive_frame(codec_ctx, frame) == 0) { // 解码成功,可处理 YUV 数据 } } av_packet_unref(&pkt); }
2.6 释放资源 avcodec_free_context(&codec_ctx); avformat_close_input(&fmt_ctx);
三、常见用途: 解码音频 PCM / 视频 YUV 数据; -配合 OpenGL / AudioTrack 进行播放; -用于播放器、剪辑工具、转码器中。
四、总结 FFmpeg 解码灵活强大,支持多种格式,适合复杂场景。 Android 中需通过 JNI 封装 C 层接口调用,并结合 OpenGL ES 或 AudioTrack 实现图像或音频播放。
|