之前遇到了一个BUG:是avcodec_parameters_copy(audioStream->codecpar, ic->streams[1]->codecpar);一直报错,最后发现是原来的视频材料就没有音频,所以会报错!!
记下这个BUG了
#include <iostream>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:6031)
extern "C"
{
#include <libavformat/avformat.h>
}
#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avcodec.lib")
#pragma comment(lib,"avutil.lib")
int main()
{
char infile[] = "test.mp4";
char outfile[] = "000.mov";
av_register_all();
AVFormatContext *ic = NULL;
avformat_open_input(&ic,infile,0,0);
if (!ic)
{
cout << "avformat_open_input failed!" << endl;
getchar();
return -1;
}
cout << "open" << infile << "success!" << endl;
AVFormatContext *oc = NULL;
avformat_alloc_output_context2(&oc, NULL, NULL, outfile);
if (!oc)
{
cerr << "avformat_alloc_output_context2 " << outfile << " failed!" << endl;
getchar();
return -1;
}
AVStream *videoStream = avformat_new_stream(oc, NULL);
AVStream *audioStream = avformat_new_stream(oc, NULL);
avcodec_parameters_copy(videoStream->codecpar, ic->streams[0]->codecpar);
avcodec_parameters_copy(audioStream->codecpar, ic->streams[1]->codecpar);
videoStream->codecpar->codec_tag = 0;
audioStream->codecpar->codec_tag = 0;
av_dump_format(ic, 0, infile, 0);
cout<<endl;
cout << "—————————以上输出的是输入的内容信息(视频+音频),下面是新生成的文件的视频+信息——————————" << endl;
cout << endl;
av_dump_format(oc, 0, outfile, 1);
int ret = avio_open(&oc->pb, outfile, AVIO_FLAG_WRITE);
if (ret < 0)
{
cerr << "avio open failed!" << endl;
getchar();
return -1;
}
ret = avformat_write_header(oc, NULL);
if (ret < 0)
{
cerr << "avformat_write_header failed!" << endl;
getchar();
}
AVPacket pkt;
for (;;)
{
int re = av_read_frame(ic, &pkt);
if (re < 0)
break;
pkt.pts = av_rescale_q_rnd(pkt.pts,
ic->streams[pkt.stream_index]->time_base,
oc->streams[pkt.stream_index]->time_base,
(AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)
);
pkt.dts = av_rescale_q_rnd(pkt.dts,
ic->streams[pkt.stream_index]->time_base,
oc->streams[pkt.stream_index]->time_base,
(AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)
);
pkt.pos = -1;
pkt.duration = av_rescale_q_rnd(pkt.duration,
ic->streams[pkt.stream_index]->time_base,
oc->streams[pkt.stream_index]->time_base,
(AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)
);
av_write_frame(oc, &pkt);
av_packet_unref(&pkt);
cout << "帧";
}
av_write_trailer(oc);
avio_close(oc->pb);
cout << endl;
cout <<"——运行成功,程序结束——" << endl;
getchar();
return 0;
}
|