c++ FFmpeg录制视频
时间: 2023-12-22 12:28:08 浏览: 268
以下是使用c++和FFmpeg录制视频的步骤:
1.初始化FFmpeg库并打开输出文件
```c++
av_register_all();
avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_file);
if (!ofmt_ctx) {
printf("Could not create output context\n");
return;
}
if (avio_open(&ofmt_ctx->pb, out_file, AVIO_FLAG_READ_WRITE) < 0) {
printf("Could not open output file '%s'", out_file);
return;
}
```
2.添加视频流和音频流
```c++
AVStream *video_st = NULL;
AVStream *audio_st = NULL;
video_st = avformat_new_stream(ofmt_ctx, NULL);
audio_st = avformat_new_stream(ofmt_ctx, NULL);
if (!video_st || !audio_st) {
printf("Failed allocating output stream\n");
return;
}
```
3.设置视频流和音频流的编码器参数
```c++
AVCodecContext *video_enc_ctx = NULL;
AVCodecContext *audio_enc_ctx = NULL;
video_enc_ctx = video_st->codec;
audio_enc_ctx = audio_st->codec;
video_enc_ctx->codec_id = ofmt_ctx->oformat->video_codec;
audio_enc_ctx->codec_id = ofmt_ctx->oformat->audio_codec;
video_enc_ctx->bit_rate = 400000;
audio_enc_ctx->bit_rate = 64000;
video_enc_ctx->width = 640;
video_enc_ctx->height = 480;
video_enc_ctx->time_base = (AVRational){1, 25};
audio_enc_ctx->sample_rate = 44100;
audio_enc_ctx->channels = 2;
audio_enc_ctx->channel_layout = AV_CH_LAYOUT_STEREO;
audio_enc_ctx->time_base = (AVRational){1, audio_enc_ctx->sample_rate};
```
4.打开视频流和音频流的编码器
```c++
AVCodec *video_enc = NULL;
AVCodec *audio_enc = NULL;
video_enc = avcodec_find_encoder(video_enc_ctx->codec_id);
audio_enc = avcodec_find_encoder(audio_enc_ctx->codec_id);
if (!video_enc || !audio_enc) {
printf("Codec not found\n");
return;
}
if (avcodec_open2(video_enc_ctx, video_enc, NULL) < 0 || avcodec_open2(audio_enc_ctx, audio_enc, NULL) < 0) {
printf("Could not open codec\n");
return;
}
```
5.写入文件头
```c++
avformat_write_header(ofmt_ctx, NULL);
```
6.循环读取视频帧和音频帧,编码并写入输出文件
```c++
AVFrame *frame = av_frame_alloc();
AVPacket pkt = {0};
while (true) {
// 读取视频帧和音频帧
AVFrame *video_frame = read_video_frame();
AVFrame *audio_frame = read_audio_frame();
if (!video_frame && !audio_frame) {
break;
}
// 编码视频帧和音频帧
if (video_frame) {
encode_video_frame(video_frame, &pkt);
}
if (audio_frame) {
encode_audio_frame(audio_frame, &pkt);
}
// 写入输出文件
av_interleaved_write_frame(ofmt_ctx, &pkt);
av_packet_unref(&pkt);
}
```
7.写入文件尾
```c++
av_write_trailer(ofmt_ctx);
```
完整代码请参考上述提供的引用。
阅读全文