ZBLOG

解码出来的音频的AVFrame如何dump出来成为pcm文件

可以使用FFmpeg库中的API将解码后的音频数据写入到PCM文件中。具体步骤如下:

  1. 打开PCM文件,创建AVFormatContext和AVOutputFormat结构体
AVFormatContext *out_ctx = NULL;
AVOutputFormat *output_fmt = av_guess_format("s16le", "pcm");
avformat_alloc_output_context2(&out_ctx, output_fmt, NULL, NULL);
  1. 创建并打开输出文件
if (!(out_fmt->flags & AVFMT_NOFILE)) {
    ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
    if (ret < 0) {
        printf("Could not open output file '%s'", out_filename);
        return -1;
    }
}
  1. 新建一个音频流
AVStream *out_stream = avformat_new_stream(out_ctx, NULL);
if (!out_stream) {
    printf("Failed to create output stream");
    return -1;
}
  1. 初始化编码器参数,并设置编码器上下文
AVCodecParameters *codec_par = out_stream->codecpar;
codec_par->codec_type = AVMEDIA_TYPE_AUDIO;
codec_par->sample_rate = sample_rate; // 设置采样率
codec_par->channels = channels; // 设置声道数
codec_par->channel_layout = av_get_default_channel_layout(channels);
codec_par->format = AV_SAMPLE_FMT_S16; // PCM格式为s16le
ret = avcodec_parameters_to_context(codec_ctx, codec_params);
if (ret < 0) {
    printf("Failed to copy codec parameters to context\n");
    return -1;
}
av_opt_set_int(codec_ctx, "strict", -2, 0); // 设置编码器为宽松模式
  1. 打开编码器并写入文件头
AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_PCM_S16LE);
if (!codec) {
    printf("Failed to find encoder\n");
    return -1;
}
ret = avcodec_open2(codec_ctx, codec, NULL);
if (ret < 0) {
    printf("Failed to open encoder\n");
    return -1;
}
avformat_write_header(out_ctx, NULL);
  1. 循环读取解码后的音频帧数据,将其写入到PCM文件中
AVFrame *frame = av_frame_alloc();
while (1) {
    ret = avcodec_receive_frame(codec_ctx, frame);
    if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) { // 编码器缓存已满,等待下一次写入
        break;
    }
    else if (ret < 0) {
        printf("Failed to receive frame from encoder\n");
        return -1;
    }

    int data_size = av_samples_get_buffer_size(NULL, channels, frame->nb_samples,
                                               AV_SAMPLE_FMT_S16, 0); // 计算每个音频帧的数据大小
    uint8_t *data = frame->data[0];
    
    // 将音频数据写入到PCM文件中
    int bytes_written = fwrite(data, 1, data_size, pcm_file);
}
  1. 最后释放资源和关闭输出文件
av_write_trailer(out_ctx);
fclose(pcm_file);
avcodec_free_context(&codec_ctx);
av_frame_free(&frame);
avformat_free_context(out_ctx);

这样就可以将解码后的音频数据写入到PCM文件中了。完整代码请参考FFmpeg库中的demuxing_decoding.c示例程序。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://sdn.0voice.com/?id=1519

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?