ffmpeg提取aac資料

NAVYSUMMER發表於2024-05-25

方法1:透過命令提取

 ffmpeg -i input.mp4 -vn -acodec aac ../output.aac

方法2:透過程式碼提取

流程圖

main.c

#include "libavutil/log.h"
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"

int main(int argc, char **argv) {
    av_log_set_level(AV_LOG_DEBUG);
    if (argc < 3) {
        av_log(NULL, AV_LOG_ERROR, "Usage:%s inputFile outputFile\n", argv[0]);
        return -1;
    }
    const char *inputFile = argv[1];
    const char *outputFile = argv[2];
    AVFormatContext *fCtx = NULL;

    int ret = avformat_open_input(&fCtx, inputFile, NULL, NULL);
    if (ret != 0) {
        av_log(NULL, AV_LOG_ERROR, "open input file:%s failed:%s\n", inputFile, av_err2str(ret));
        return -1;
    }
    ret = avformat_find_stream_info(fCtx, NULL);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "open input file stream failed:%s\n", av_err2str(ret));
        avformat_close_input(&fCtx);
        return -1;
    }
    int audioIndex = av_find_best_stream(fCtx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
    if (audioIndex < 0) {
        av_log(NULL, AV_LOG_ERROR, "find best stream failed:index:%d\n", audioIndex);
        avformat_close_input(&fCtx);
        return -1;
    }
    av_log(NULL,AV_LOG_INFO,"audioIndex=%d\n",audioIndex);
    FILE *dst = fopen(outputFile, "wb");
    if (dst == NULL) {
        av_log(NULL, AV_LOG_ERROR, "open output file: %s failed", outputFile);
        avformat_close_input(&fCtx);
        return -1;
    }
    AVPacket *packet = av_packet_alloc();
    while (av_read_frame(fCtx, packet) == 0) {
        if (packet->stream_index == audioIndex) {
            size_t size = fwrite(packet->data, 1, packet->size, dst);
            if (size != packet->size) {
                av_log(NULL,AV_LOG_ERROR,"write size:%zu,packet size:%d",size,packet->size);
                fclose(dst);
                avformat_close_input(&fCtx);
                return -1;
            }

        }
        av_packet_unref(packet);

    }

    if (fCtx!=NULL){
        avformat_close_input(&fCtx);
    }
    fclose(dst);

    return 0;

}

Makefile

TARGET=main
SRC=main.c
CC=gcc
CFLAGS=-I /usr/local/ffmpeg/include
LDFLAGS=-L /usr/local/ffmpeg/lib
LDFLAGS+= -lavutil -lavformat -lavcodec
all:$(TARGET)
$(TARGET):$(SRC)
	$(CC) $(SRC) $(CFLAGS) $(LDFLAGS) -o $(TARGET)
clean:
	rm -rf $(TARGET)

  

相關文章