Codecs in audio programming are algorithms used to compress and decompress audio data. The term "codec" is short for "coder-decoder."
Codecs are used to reduce the size of audio files and streams, making them easier to store and transmit over networks. There are two main types of audio codecs: lossless and lossy.
Lossless codecs compress audio data without losing any information. When the data is decompressed, it is restored to its original form without any loss of quality. Lossless codecs are often used in professional audio applications where high fidelity is critical.
Lossy codecs, on the other hand, compress audio data by discarding some information that is deemed less important. When the data is decompressed, some loss of quality is inevitable. Lossy codecs are commonly used in consumer audio applications, such as music streaming services, where smaller file sizes are more important than perfect fidelity.
Using the Encoder and Decoder Classes
Switchboard SDK provides easy-to-use classes to encode and decode audio data. Currently the supported formats are the following:
Decoding an Audio File
We can load an audio file using our
FileReader and use the
Mp3Decoder class to decode MP3 data to PCM audio data.
const std::string audioFilePath = "myFile.mp3";
const std::vector<uint8> audioFileData = FileReader::read(audioFilePath);
const bool success = Mp3Decoder::decode(audioFileData, rawAudioData, sampleRate, numberOfChannels);
Encoding an Audio File
We can use the
Mp3Encoder class to encode raw PCM data to MP3 with the following code snippet:
const std::string audioFilePath = "myFile.raw";
const sampleRate = 44100;
const std::vector<int16> audioFileData = FileReader::read(audioFilePath);
const vector<uint8> output = Mp3Encoder::encode(audioFileData, sampleRate);