gpt4 book ai didi

c++ - 解码 m4a 和转储 PCM 数据会返回噪声

转载 作者:行者123 更新时间:2023-11-28 03:06:45 25 4
gpt4 key购买 nike

我正在使用下面的代码(根据 libavcodec 中给出的示例修改)来解码音频文件

int main(int argc, char **argv)
{
av_register_all();
avcodec_register_all();

char *filename = argv[1];
char *outfilename = argv[2];

FILE *outfile;

AVCodec *codec;
AVCodecContext *c= NULL;
AVPacket avpkt;
AVFrame *frame = av_frame_alloc();

printf("Decode audio file %s to %s\n", filename, outfilename);

outfile = fopen(outfilename, "wb");
if (!outfile) {
fprintf(stderr, "Could not write to %s\n", outfilename);
av_free(c);
exit(1);
}

AVFormatContext *format_context = NULL;
avformat_open_input(&format_context, filename, NULL, NULL);
printf("Opened format input\n");

int find_result = avformat_find_stream_info(format_context, NULL);
if (find_result < 0) {
fprintf(stderr, "Cannot find stream info\n");
avformat_close_input(&format_context);
exit(-1);
}

int audio_stream_idx = av_find_best_stream(format_context, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);

if (audio_stream_idx < 0) {
fprintf(stderr,"Couldn't find stream information\n");
exit(-1);
}

// Get a pointer to the codec context for the audio stream
c = format_context->streams[audio_stream_idx]->codec;
av_opt_set_int(c, "refcounted_frames", 1, 0);

if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(-1);
}

// read the audio frames
int ret, got_frame;
while (1) {
if ((ret = av_read_frame(format_context, &avpkt)) < 0)
break;
if (avpkt.stream_index == audio_stream_idx) {
avcodec_get_frame_defaults(frame);
got_frame = 0;
ret = avcodec_decode_audio4(c, frame, &got_frame, &avpkt);
if (ret < 0) {
fprintf(stderr, "Error decoding audio\n");
continue;
}

if (got_frame) {
// write to disk
fwrite(frame->extended_data[0], 1, frame->linesize[0], outfile);
}
}
av_free_packet(&avpkt);
}

fclose(outfile);

printf("Finished\n");
if (c)
avcodec_close(c);
avformat_close_input(&format_context);
av_frame_free(&frame);
}

我尝试了 .mp3.m4a 文件; .mp3 文件工作正常但不适用于 .m4a 文件。有帮助吗?

最佳答案

大多数 aac 文件都是 FLOAT 格式,即 AV_SAMPLE_FMT_FLTP,而 libao 等库只能播放整数格式的音频,即AV_SAMPLE_FORMAT_S16

因此,您需要使用 libavresample 对音乐重新采样并根据需要转换格式。

关于c++ - 解码 m4a 和转储 PCM 数据会返回噪声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com