ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ### 抽取音视频数据的步骤 ***** 从一个多媒体文件中抽取音频数据 1.av_init_packet() -------- 初始化一个数据包结构体 --从多媒体文件中读取的每一个数据包都可以房在这个初始化的结构体里 2.av_find_best_stream() 在多媒体文件中找到最好的一路流 3.av_read_frame() / av_packet_unref(); 将流里的数据包进行相应的处理。写入一个文件里 unref 将包释放掉 ### 示例代码 ***** ``` extern "C" { #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "libswscale/swscale.h" #include "libavdevice/avdevice.h" #include "libavutil/time.h" }; #include <stddef.h> #include <stdint.h> #include <tchar.h> #include <stdio.h> int main() { int ret; //返回值 调用成功与否 char *src = NULL; char* dst = NULL; //定义一个上下文 AVFormatContext* fmt_ctx = NULL; AVPacket pkt; av_log_set_level(AV_LOG_INFO); av_register_all(); //注册所有的编解码器 //1.read two params from console src = "./test.mp4"; dst = "./test44.mp4"; if (!src || !dst) { av_log(NULL, AV_LOG_ERROR, "Cant open file"); goto __fatl; } //打开一个多媒体文件 ret = avformat_open_input(&fmt_ctx,src, NULL, NULL); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "cant open file"); goto __fatl; } FILE* dst_fd = fopen(dst, "wb"); if (!dst_fd) { av_log(NULL, AV_LOG_ERROR, "Cant open out file!\n"); avformat_close_input(&fmt_ctx); goto __fatl; } av_dump_format(fmt_ctx, 0, src, 0);//最后一个1代表输出 0代表输入 //2.get stream ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0); //拿到的是流的index值 if (ret < 0) { av_log(NULL,AV_LOG_ERROR, "Cant find the best stream !\n"); avformat_close_input(&fmt_ctx); fclose(dst_fd); goto __fatl; } int audio_index = ret; int len ; av_init_packet(&pkt); // 初始化包 //3.write audio data to aac file. while(av_read_frame(fmt_ctx, &pkt) >= 0) { if (pkt.stream_index == audio_index) { char adts_header_buf[7]; //adts_header(); len = fwrite(pkt.data, 1, pkt.size, dst_fd); if (len != pkt.size) { av_log(NULL, AV_LOG_WARNING, "warning, length of data not equal size of pkt!\n"); goto __fatl; } } av_packet_unref(&pkt); // 释放包 } avformat_close_input(&fmt_ctx); //关闭输出文件 if (dst_fd) { fclose(dst_fd); } avformat_close_input(&fmt_ctx); __fatl: system("pause"); return 0; }