您的位置:首页 > 编程语言

ffmpeg将flv解封装为h264和mp3文件测试代码

2016-08-28 13:45 501 查看
#include <stdio.h>

#define __STDC_CONSTANT_MACROS

#ifdef _WIN32
extern "C"{
#include "libavformat/avformat.h"
};
#else
#ifdef __cplusplus
extern "C"{
#endif
#include <libavformat/avformat.h>
#ifdef __cplusplus
};
#endif
#endif

int main(int argc, char* argv[]){
AVFormatContext *ifmt_ctx = NULL;
AVPacket pkt;
int ret, i;
int videoindex = -1, audioindex = -1;
const char *in_filename = "in.flv";
const char *out_filename_v = "out.h264";
const char *out_filename_a = "out.mp3";
av_register_all();
if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
printf("Could not open input file.");
return -1;
}
if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
printf("Failed to retrieve input stream information");
return -1;
}
videoindex = -1;
for (i = 0; i<ifmt_ctx->nb_streams; i++) {
if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
videoindex = i;
}
else if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
audioindex = i;
}
}
printf("===========================\Input Video===========================\n");
av_dump_format(ifmt_ctx, 0, in_filename, 0);
printf("==================================================================\n");
FILE *fp_audio = fopen(out_filename_a, "wb+");
FILE *fp_video = fopen(out_filename_v, "wb+");
while (av_read_frame(ifmt_ctx, &pkt) >= 0) {
if (pkt.stream_index == videoindex) {
printf("Write Video Packet. size:%d\tpts:%lld\n", pkt.size, pkt.pts);
fwrite(pkt.data, 1, pkt.size, fp_video);
}
else if (pkt.stream_index == audioindex) {
/*注意:FLV/MP4/MKV等格式中的AAC码流(上述封装格式中的AAC的AVPacket中的数据缺失了7字节的ADTS文件头)*/
printf("Write Audio Packet. size:%d\tpts:%lld\n", pkt.size, pkt.pts);
fwrite(pkt.data, 1, pkt.size, fp_audio);
}
av_free_packet(&pkt);
}
fclose(fp_video);
fclose(fp_audio);
avformat_close_input(&ifmt_ctx);
if (ret < 0 && ret != AVERROR_EOF) {
printf("Error occurred.\n");
return -1;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: