Matin Kh
Matin Kh

Reputation: 5178

Encoding audio data using ffmpeg

I am receiving a byte array (int8_t*) and I would like to use FFMPEG to encode it into FLAC. All the examples I found are reading data from files, which is not the case for me. Following the original documents (see here), I came up with the following solution:

#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;
}

I have two main issues with the above solution:

  1. I did not specify what the final encoding should be (for example, MP3, FLAC, etc), which makes me wonder if I'm using FFMPEG library correctly?

  2. Do I have all the necessary information about the source - original audio data? I am not certain if I have all the necessary information to perform the encoding.

Upvotes: 3

Views: 1679

Answers (1)

the kamilz
the kamilz

Reputation: 1988

You are nearly there, follow this example: https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/encode_audio.c

Answer to 1st question: There you'll see codec = avcodec_find_encoder(AV_CODEC_ID_MP2).
In your case, you guessed it, it probably will be codec = avcodec_find_encoder(AV_CODEC_ID_FLAC) and check/fix other values accordingly.

As for 2nd one... I'm sure you'll find out yourself, especially you must set this correctly (line 158) c->sample_fmt = AV_SAMPLE_FMT_S16 according to what your int8_t array formatted.

Hope that helps.

Upvotes: 1

Related Questions