FFmpeg:将原始数据编码为FLAC格式并解码回原始数据(附完整源代码)

本文详细介绍了如何使用FFmpeg库将原始音频数据编码为FLAC格式,并将其解码回原始数据。提供了完整的源代码示例,适合对音视频处理感兴趣的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FFmpeg:将原始数据编码为FLAC格式并解码回原始数据

#include "libavcodec/avcodec.h"
#include "libavutil/channel_layout.h"
#include "libavutil/common.h"
#include "libavutil/samplefmt.h"

#define NUMBER_OF_AUDIO_FRAMES 200
#define NAME_BUFF_SIZE 100

/* generate i-th frame of test audio */
static int generate_raw_frame(uint16_t *frame_data, int i, int sample_rate,
                              int channels, int frame_size)
{
   
    int j, k;

    for (j = 0; j < frame_size; j++) {
   
        frame_data[channels * j] = 10000 * ((j / 10 * i) % 2);
        for (k = 1; k < channels; k++)
            frame_data[channels * j + k] = frame_data[channels * j] * (k + 1);
    }
    return 0;
}

static int init_encoder(const AVCodec *enc, AVCodecContext **enc_ctx,
                        const AVChannelLayout *ch_layout, int sample_rate)
{
   
    AVCodecContext *ctx;
    int result;
    char name_buff[NAME_BUFF_SIZE];

    av_channel_layout_describe(ch_layout, name_buff, NAME_BUFF_SIZE);
    av_log(NULL, AV_LOG_INFO, "channel layout: %s, sample rate: %i\n", name_buff, sample_rate);

    ctx = avcodec_alloc_context3(enc);
    if (!ctx) {
   
        av_log(NULL, AV_LOG_ERROR, "Can't allocate encoder context\n");
        return AVERROR(ENOMEM);
    }

    ctx->sample_fmt = AV_SAMPLE_FMT_S16;
    ctx->sample_rate = sample_rate;
    av_channel_layout_copy(&ctx->ch_layout, ch_layout);

    result = avcodec_open2(ctx, enc, NULL);
    if (result < 0) {
   
        av_log(ctx, AV_LOG_ERROR, "Can't open encoder\n");
        return result;
    }

    *enc_ctx = ctx;
    return 0;
}

static int init_decoder(const AVCodec *dec, AVCodecContext **dec_ctx,
                        const AVChannelLayout *ch_layout)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源代码大师

赏点狗粮吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值