C言語でFFmpegを呼び出す方法は何ですか?
C言語でFFmpegライブラリを呼び出す方法は、FFmpegが提供するAPI関数を使用することです。以下は音声およびビデオ処理を行うためにFFmpegライブラリを使用する基本的な手順です。
- FFmpegのヘッダーファイルをインクルードする。
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
- FFmpegライブラリを初期化します。
av_register_all();
- ファイルを開く:
AVFormatContext *formatContext = NULL;
if(avformat_open_input(&formatContext, inputFileName, NULL, NULL) != 0) {
// 打开文件失败,处理错误
}
- 音声およびビデオストリームの情報を取得します。
if (avformat_find_stream_info(formatContext, NULL) < 0) {
// 获取流信息失败,处理错误
}
- ビデオストリームとオーディオストリームを検索する:
int videoStreamIndex = -1;
int audioStreamIndex = -1;
for (int i = 0; i < formatContext->nb_streams; i++) {
if (formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStreamIndex = i;
} else if (formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
audioStreamIndex = i;
}
}
- ビデオデコーダーをオープンしてください。
AVCodecContext *videoCodecContext = avcodec_alloc_context3(NULL);
avcodec_parameters_to_context(videoCodecContext, formatContext->streams[videoStreamIndex]->codecpar);
AVCodec *videoCodec = avcodec_find_decoder(videoCodecContext->codec_id);
avcodec_open2(videoCodecContext, videoCodec, NULL);
- ビデオフレームをデコードする。
AVPacket *packet = av_packet_alloc();
AVFrame *frame = av_frame_alloc();
while (av_read_frame(formatContext, packet) >= 0) {
if (packet->stream_index == videoStreamIndex) {
avcodec_send_packet(videoCodecContext, packet);
while (avcodec_receive_frame(videoCodecContext, frame) == 0) {
// 处理视频帧数据
}
}
av_packet_unref(packet);
}
- デコーダーを閉じ、入力ファイルを閉じます。
avcodec_free_context(&videoCodecContext);
avformat_close_input(&formatContext);
FFmpegライブラリを使用して音声および動画処理を行うための基本操作について説明しましたが、実際のニーズに応じて具体的な方法や機能を調整できます。また、FFmpegが提供する他のAPI関数を使用して音声および動画のエンコード、パッケージング、フィルタリングなどの操作も可能です。