c++ - 使用 ffmpeg 编码音频数据

标签 c++ ffmpeg

我正在接收一个字节数组 (int8_t*),我想使用 FFMPEG将其编码为 FLAC。我找到的所有示例都是从文件中读取数据,而我不是这样。根据原始文档(参见 here),我想出了以下解决方案:

#include "libavcodec/avcodec.h"

// ...

// params:
//  audioData: original audio data
//  len: length of the byte array (audio data)
//  sampleRate: sample rate of the original audio data
//  frameSize: frame size of the original data
uint8_t* encodeToFlac(uint8_t* audioData, int len, int sampleRate, int frameSize) {
  uint8_t* convertedAudioData;

  // Context information
  AVCodecContext* context = avcodec_alloc_context();
  context->bit_rate = 64000;
  context->sample_rate = sampleRate;
  context->channels = 2;
  context->frame_size = frameSize;

  short* samples = malloc(frameSize * 2 * context->channels);
  int outAudioDataSize = len * 2;
  convertedAudioData = malloc(outAudioDataSize);
  int outSize = avcodec_encode_audio(c, convertedAudioData, outAudioDataSize, samples);

  return convertedAudioData;
}

上述解决方案有两个主要问题:

  1. 我没有指定最终编码应该是什么(例如,MP3、FLAC 等),这让我想知道我是否正确使用了 FFMPEG 库?

  2. 我是否拥有有关来源(原始音频数据)的所有必要信息?我不确定我是否拥有执行编码所需的所有必要信息。

最佳答案

你快到了,按照这个例子:https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/encode_audio.c

第一个问题的答案: 在那里你会看到 codec = avcodec_find_encoder(AV_CODEC_ID_MP2)
在您的情况下,您猜对了,它可能是 codec = avcodec_find_encoder(AV_CODEC_ID_FLAC) 并相应地检查/修复其他值。

至于第二个......我相信你会发现自己,特别是你必须正确设置它(第 158 行)c->sample_fmt = AV_SAMPLE_FMT_S16 根据你的int8_t 格式化数组。

希望对您有所帮助。

关于c++ - 使用 ffmpeg 编码音频数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56368106/

相关文章:

video - libavcodec 获取视频时长和帧率

c++ - 派生类错误

c++ - 如何在 C++ 中的 visual studio 2010 中添加 .a 文件

ffmpeg - 是否保证整个流的数据包持续时间是统一的?

batch-file - MP3 + JPG 同名

c - 调查视频损坏的工具/技术——ffmpeg/libavcodec

C++: myfile.open ("example.txt") 行:找不到文件?

c++将仿函数和参数传递给一个方法

c++ - 处理 Qt5 中 QRegularExpressions 中的重音字母

php - 如何使用ffmpeg在多个区域添加水印?