A simple C++ library for reading and writing audio files.

Overview

AudioFile

Version License Language

A simple header-only C++ library for reading and writing audio files.

Current supported formats:

  • WAV
  • AIFF

Author

AudioFile is written and maintained by Adam Stark.

http://www.adamstark.co.uk

Usage

Create an AudioFile object:

#include "AudioFile.h"

AudioFile<double> audioFile;

Load an audio file:

audioFile.load ("/path/to/my/audiofile.wav");

Get some information about the loaded audio:

int sampleRate = audioFile.getSampleRate();
int bitDepth = audioFile.getBitDepth();

int numSamples = audioFile.getNumSamplesPerChannel();
double lengthInSeconds = audioFile.getLengthInSeconds();

int numChannels = audioFile.getNumChannels();
bool isMono = audioFile.isMono();
bool isStereo = audioFile.isStereo();

// or, just use this quick shortcut to print a summary to the console
audioFile.printSummary();

Access the samples directly:

int channel = 0;
int numSamples = audioFile.getNumSamplesPerChannel();

for (int i = 0; i < numSamples; i++)
{
	double currentSample = audioFile.samples[channel][i];
}

Replace the AudioFile audio buffer with another

// 1. Create an AudioBuffer 
// (BTW, AudioBuffer is just a vector of vectors)

AudioFile<double>::AudioBuffer buffer;

// 2. Set to (e.g.) two channels
buffer.resize (2);

// 3. Set number of samples per channel
buffer[0].resize (100000);
buffer[1].resize (100000);

// 4. do something here to fill the buffer with samples, e.g.

#include <math.h> // somewhere earler (for M_PI and sinf())

// then...

int numChannels = 2;
int numSamplesPerChannel = 100000;
float sampleRate = 44100.f;
float frequency = 440.f;

for (int i = 0; i < numSamplesPerChannel; i++)
{
    float sample = sinf (2. * M_PI * ((float) i / sampleRate) * frequency) ;
    
    for (int channel = 0; channel < numChannels; channel++)
         buffer[channel][i] = sample * 0.5;
}

// 5. Put into the AudioFile object
bool ok = audioFile.setAudioBuffer (buffer);

Resize the audio buffer

// Set both the number of channels and number of samples per channel
audioFile.setAudioBufferSize (numChannels, numSamples);

// Set the number of samples per channel
audioFile.setNumSamplesPerChannel (numSamples);

// Set the number of channels
audioFile.setNumChannels (int numChannels);

Set bit depth and sample rate

audioFile.setBitDepth (24);
audioFile.setSampleRate (44100);

Save the audio file to disk

// Wave file (implicit)
audioFile.save ("path/to/desired/audioFile.wav");

// Wave file (explicit)
audioFile.save ("path/to/desired/audioFile.wav", AudioFileFormat::Wave);

// Aiff file
audioFile.save ("path/to/desired/audioFile.aif", AudioFileFormat::Aiff);

Examples

Please see the examples folder for some examples on library usage.

A Note On Types

AudioFile is a template class and so it can be instantiated using floating point precision:

AudioFile<float> audioFile;

...or double precision:

AudioFile<double> audioFile;

This simply reflects the data type you would like to use to store the underlying audio samples. You can still read or write 8, 16 or 24-bit audio files, regardless of the type that you use (unless your system uses a precision for floats less than your desired bit depth).

I have heard of people using the library with other types, but I have not designed for those cases. Let me know if you are interested in this supporting a specific type more formally.

Error Messages

By default, the library logs error messages to the console to provide information on what has gone wrong (e.g. a file we tried to load didn't exist).

If you prefer not to see these messages, you can disable this error logging behaviour using:

audioFile.shouldLogErrorsToConsole (false);

Versions

1.0.9 - 23rd January 2021
  • Faster loading of audio files
  • Bug fixes
1.0.8 - 18th October 2020
  • CMake support
  • Construct instances with a file path
  • Bug fixes
1.0.7 - 3rd July 2020
  • Support for 32-bit audio files
  • Support for multi-channel audio files
  • Reading/writing of iXML data chunks
1.0.6 - 29th February 2020
  • Made error logging to the console optional
  • Fixed lots of compiler warnings
1.0.5 - 14th October 2019
  • Added include of to better support Visual Studio
1.0.4 - 13th October 2019
  • Changed to a header-only library. Now you can just include AudioFile.h
  • Bug fixes
1.0.3 - 28th October 2018
  • Bug fixes
  • Documentation updates
1.0.2 - 6th June 2017
  • Bug fixes

Contributions

Want to Contribute?

If you would like to submit a pull request for this library, please do! But kindly follow the following simple guidelines...

  • Make the changes as concise as is possible for the change you are proposing
  • Avoid unnecessarily changing a large number of lines - e.g. commits changing the number of spaces in indentations on all lines (and so on)
  • Keep to the code style of this library which is the JUCE Coding Standards

License

Copyright (c) 2017 Adam Stark

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

Comments
  • Support for higher bitrates?

    Support for higher bitrates?

    Hello!

    I recently replaced dr_wav with your wonderful AudioFile library. I've been getting reports from some of my users that .wav files that previously loaded and play fine no longer work. I've found that the reason is that the .wav files that they were using were greater than than 24-bit.

    The bitrates supported by dr_wav are:

    Unsigned 8-bit PCM Signed 12-bit PCM Signed 16-bit PCM Signed 24-bit PCM Signed 32-bit PCM IEEE 32-bit floating point IEEE 64-bit floating point

    Would it be possible to support these .wav file formats?

    Thanks! Bret

    opened by clone45 8
  • -Wsign-compare warnings

    -Wsign-compare warnings

    When using this library, I get a few warnings related to -Wsign-compare. Are there any plans on fixing it? It shouldn't be too hard.

    In file included from src/main.cpp:3:
    src/../include/AudioFile.h: In instantiation of ‘bool AudioFile<T>::decodeWaveFile(std::vector<unsigned char>&) [with T = double]’:
    src/../include/AudioFile.h:403:16:   required from ‘bool AudioFile<T>::load(std::string) [with T = double; std::string = std::__cxx11::basic_string<char>]’
    src/main.cpp:20:40:   required from here
    src/../include/AudioFile.h:468:28: warning: comparison of integer expressions of different signedness: ‘int32_t’ {aka ‘int’} and ‘uint32_t’ {aka ‘unsigned int’
    } [-Wsign-compare]
      468 |     if ((numBytesPerSecond != (numChannels * sampleRate * bitDepth) / 8) || (numBytesPerBlock != (numChannels * numBytesPerSample)))
          |         ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    src/../include/AudioFile.h: In instantiation of ‘bool AudioFile<T>::decodeAiffFile(std::vector<unsigned char>&) [with T = double]’:
    src/../include/AudioFile.h:407:16:   required from ‘bool AudioFile<T>::load(std::string) [with T = double; std::string = std::__cxx11::basic_string<char>]’
    src/main.cpp:20:40:   required from here
    src/../include/AudioFile.h:599:90: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<unsigned char>::size_type’ {aka
    long unsigned int’} [-Wsign-compare]
      599 |     if ((soundDataChunkSize - 8) != totalNumAudioSampleBytes || totalNumAudioSampleBytes > (fileData.size() - samplesStartIndex))
          |                                                                 ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    src/../include/AudioFile.h: In instantiation of ‘int AudioFile<T>::getIndexOfString(std::vector<unsigned char>&, std::string) [with T = double; std::string = s
    td::__cxx11::basic_string<char>]’:
    src/../include/AudioFile.h:428:28:   required from ‘bool AudioFile<T>::decodeWaveFile(std::vector<unsigned char>&) [with T = double]’
    src/../include/AudioFile.h:403:16:   required from ‘bool AudioFile<T>::load(std::string) [with T = double; std::string = std::__cxx11::basic_string<char>]’
    src/main.cpp:20:40:   required from here
    src/../include/AudioFile.h:1007:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<unsigned char>::size_type’ {aka
    ‘long unsigned int’} [-Wsign-compare]
     1007 |     for (int i = 0; i < source.size() - stringLength;i++)
          |                     ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    src/../include/AudioFile.h: In instantiation of ‘void AudioFile<T>::clearAudioBuffer() [with T = double]’:
    src/../include/AudioFile.h:490:5:   required from ‘bool AudioFile<T>::decodeWaveFile(std::vector<unsigned char>&) [with T = double]’
    src/../include/AudioFile.h:403:16:   required from ‘bool AudioFile<T>::load(std::string) [with T = double; std::string = std::__cxx11::basic_string<char>]’
    src/main.cpp:20:40:   required from here
    src/../include/AudioFile.h:950:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<std::vector<double, std::allocato
    r<double> >, std::allocator<std::vector<double, std::allocator<double> > > >::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
      950 |     for (int i = 0; i < samples.size();i++)
    

    Great job on the library by the way!! Super useful and lightweight :)

    opened by marioortizmanero 7
  • unordered_map link problem

    unordered_map link problem

    There is a link problem in AudioFile.cpp at aiffSampleRateTable, please change the class in unordered_map template definition from int to long or uint32_t, etc..., to fix it.

    std::unordered_map <long, std::vector<uint8_t> > aiffSampleRateTable

    Nice code btw.

    opened by jpcordovae 7
  • Support for multi-channel files

    Support for multi-channel files

    Added support for multi-channel files. Did not have to do a lot - mainly adding tests to make sure it works. Currently testing writing 8-channel files for all formats and reading with 8-channel wav 24bit, 48k Updated python script to generate headers as well.

    enhancement 
    opened by Sidelobe 6
  • Get size of AudioFile, to assign to OpenAL Soft buffer

    Get size of AudioFile, to assign to OpenAL Soft buffer

    Hi Mr. Adam Stark,

    May I know how to get the size of an AudioFile because I want to assign to OpenAL Soft generated buffer to store the AudioBuffer. I am referring to the tutorial here (LINE 157, 163, 169). Sorry for the inconvenience.

    Thank you Mr. Adam Stark

    opened by rfdnl 5
  • Overload AudioFile::load to accept a memory load

    Overload AudioFile::load to accept a memory load

    It would be very helpful for directly loading decrypted .wav files. I noted it is almost done with AudioFile::decodeWaveFile, but it is a private method, so maybe an overloaded option of AudioFile::load would be great, accepting (void* data, size_t size) or std::vector<uint8_t> Thanks for this awesome library

    opened by rilpires 4
  • Update AudioFile.cpp

    Update AudioFile.cpp

    Replaced the std::cout statements with exceptions, because a library shouldn't display any error messages.

    Fixed bug in load function, where end iterator was not initialized. Introduced rawread function to read the bytes instead.

    opened by edwardkarak 4
  • Reading & Writing wav with 32-bit resolution

    Reading & Writing wav with 32-bit resolution

    I added support for reading and writing of wave files with 32bit resolution with corresponding tests.

    The unit tests currently use "hard-coded" reference data (got it through Matlab's audioread) and compare the first 64 samples of audio.

    Also, I'm creating the output directory for the unit test in case it doesn't exist yet. Added it to .gitignore as well.

    I haven't had time to look into the headers you use as reference, but guess makeHeaders.py is what I'm looking for.

    enhancement 
    opened by Sidelobe 4
  • Only one hpp file

    Only one hpp file

    Due to the fact that you're implementing a Template, to avoid issues with different compilers, you should consider having only one .hpp file with the full template definition there.

    opened by xavier7179 4
  • Make AudioFile.h compatible with more compilation options.

    Make AudioFile.h compatible with more compilation options.

    Make AudioFile.h compatible with -Wall -Wextra -pedantic -Werror compilation options for GCC (And /W4 and /WX for MSVC). This will make it easier project compatible with many projects. You can use GitHub Actions to easly run tests on Linux, Windows and Mac.

    opened by MatthieuHernandez 3
  • Max-int overflow

    Max-int overflow

    Hi Adam,

    In a short test, filling the buffer with some sine values, I noticed the resulting wave had a negative peak value, where it should have been the max positive value. It seems to be that a 1.0 float value in the buffer is saved as 32768 (for the 16-bit format). This is the piece of code for saving the file:

                else if (bitDepth == 16)
                {
                    int16_t sampleAsInt = (int16_t) (samples[channel][i] * (T)32768.);
                    addInt16ToFileData (fileData, sampleAsInt);
                }
    
    

    The easiest solution would be to replace the 32768 value by a 32767, hereby 'losing' the max nagative -32768 value. Or using an intermediate 32-bit value, which is clipped between 32767 and -32768 afterwards.

    Regards and thanks for your code,

    Ruud

    opened by Slay68 3
  • Any support for short type?

    Any support for short type?

    Hi, i met a error when using short type, "This version of AudioFile only supports floating point sample formats"

    Will AudioFile support short type in the future? Thanks.

    opened by didadida-r 0
  • Use-of-uninitialized-value waring with MSAN in AudioFile

    Use-of-uninitialized-value waring with MSAN in AudioFile

    Hi, Adam: When I use msan to run AudioFile's exmaple program, it outputs the following error message:

    Uninitialized bytes in MemcmpInterceptorCommon at offset 48 inside [0x7fffcb727450, 256)
    ==89831==WARNING: MemorySanitizer: use-of-uninitialized-value
        #0 0x5627f25d0a0e in __interceptor_memcmp (/workspace/test/msan/AudioFile/examples/Examples+0x5da0e) (BuildId: d090aa71c8d408cc1981b1bbc768ff7bf3daf5a3)
        #1 0x7f3f4348d071 in std::ctype<char>::_M_widen_init() const (/lib/x86_64-linux-gnu/libstdc++.so.6+0xd7071) (BuildId: 725ef5da52ee6d881f9024d8238a989903932637)
        #2 0x7f3f434f280f in std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&) (/lib/x86_64-linux-gnu/libstdc++.so.6+0x13c80f) (BuildId: 725ef5da52ee6d881f9024d8238a989903932637)
        #3 0x5627f2620132 in examples::writeSineWaveToAudioFile() (/workspace/test/msan/AudioFile/AudioFile/Examples+0xad132) (BuildId: d090aa71c8d408cc1981b1bbc768ff7bf3daf5a3)
        #4 0x5627f2620010 in main (/workspace/test/msan/AudioFile/examples/Examples+0xad010) (BuildId: d090aa71c8d408cc1981b1bbc768ff7bf3daf5a3)
        #5 0x7f3f430b0d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f) (BuildId: 89c3cb85f9e55046776471fed05ec441581d1969)
        #6 0x7f3f430b0e3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e3f) (BuildId: 89c3cb85f9e55046776471fed05ec441581d1969)
        #7 0x5627f2597ee4 in _start (/workspace/test/msan/AudioFile/examples/Examples+0x24ee4) (BuildId: d090aa71c8d408cc1981b1bbc768ff7bf3daf5a3)
    
    SUMMARY: MemorySanitizer: use-of-uninitialized-value (/workspace/test/msan/AudioFile/examples/Examples+0x5da0e) (BuildId: d090aa71c8d408cc1981b1bbc768ff7bf3daf5a3) in __interceptor_memcmp
    Exiting
    

    Although this does not necessarily bring any high-risk effects, I still think it is an abnormal result, and hope to get your attention

    Verification steps:

    git clone https://github.com/adamstark/AudioFile.git
    cd AudioFile/
    git checkout develop
    mkdir check_build && cd check_build
    cmake ../ -DCMAKE_C_COMPILER=clang  -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_FLAGS="-fsanitize=memory" -DCMAKE_CXX_FLAGS="-fsanitize=memory" 
    make -j 
    cd examples
    ./Examples
    

    enviroment: Ubuntu 22.04 LTS Linux lab-pro 4.15.0-147-generic gcc (Ubuntu 11.2.0-19ubuntu1) 11.2.0 Ubuntu clang version 14.0.6

    Thanks & Best regards !

    opened by Yhcrown 0
  • Multiple inclusion

    Multiple inclusion

    Hi Adam,

    This is a nice header-only library.

    Quick Q: If the header is included in two different cpp files, won't you get two independent copies of the aiff sample rate table, because the static will be scoped to within the cpp file that included it?

    // Pre-defined 10-byte representations of common sample rates
    static std::unordered_map <uint32_t, std::vector<uint8_t>> aiffSampleRateTable = {
        {8000, {64, 11, 250, 0, 0, 0, 0, 0, 0, 0}},
    
    opened by whaleygeek 3
  • Saving file as it is streamed

    Saving file as it is streamed

    I am working on a project in which data keeps streaming in and I need to save the frames to wav as they come in. I cannot wait until I have all the data to save and the sequence load_wav-add_samplesa-save_wav seems wasteful and I may lose frames. Is there a better way to "flush" the frames to disk without having to close the file all the time?

    opened by Yahsfa 3
Owner
Adam Stark
Developer working on the MiMU Gloves, Endlesss, audio analysis and all things musical
Adam Stark
LibMEI is a C++ library for reading and writing MEI files

C++ library and Python bindings for the Music Encoding Initiative format

Distributed Digital Music Archives and Libraries Lab 58 Nov 17, 2022
PortAudio is a portable audio I/O library designed for cross-platform support of audio

PortAudio is a cross-platform, open-source C language library for real-time audio input and output.

PortAudio 786 Jan 1, 2023
A simple and easy-to-use audio library based on miniaudio

raudio A simple and easy-to-use audio library based on miniaudio raudio forks from raylib.audio module to become an standalone library. Actually, it w

Ray 67 Dec 21, 2022
simple audio mixer for native and web

?? auph ?? Trivial audio mixer API for native and web targets. Online Demo ⚠️ Work in progress! API is constantly changing. The native playback at the

Elias Ku 13 Jul 1, 2022
SimplE Lossless Audio

SELA SimplE Lossless Audio A lossless audio codec which aims to be as simple as possible while still having good enough compression ratios. Code Quali

Ratul Saha 207 Sep 13, 2022
An audio mixer that supports various file formats for Simple Directmedia Layer.

An audio mixer that supports various file formats for Simple Directmedia Layer.

Simple Directmedia Layer 198 Dec 26, 2022
A simple CLI to extract & save artwork of a 🎵 music/audio file.

artwork-extractor A simple CLI to extract & save artwork of a ?? music/audio file. Usage Dependencies MediaInfoLib On Debian based distros, one may in

Hitesh Kumar Saini 5 Aug 4, 2021
ASS: Audio Stupidly Simple

A single header library for audio decoding and playback

Danny Angelo Carminati Grein 32 Nov 13, 2022
C++ library for audio and music analysis, description and synthesis, including Python bindings

Essentia Essentia is an open-source C++ library for audio analysis and audio-based music information retrieval released under the Affero GPL license.

Music Technology Group - Universitat Pompeu Fabra 2.3k Jan 7, 2023
C library for cross-platform real-time audio input and output

libsoundio C library providing cross-platform audio input and output. The API is suitable for real-time software such as digital audio workstations as

Andrew Kelley 1.6k Jan 6, 2023
C++ Audio and Music DSP Library

_____ _____ ___ __ _ _____ __ __ __ ____ ____ / \\_ \\ \/ / |/ \| | | | \_ \/ \ | Y Y \/ /_ \> <| | Y Y \ | |_|

Mick Grierson 1.4k Jan 7, 2023
Single file audio playback and capture library written in C.

A single file library for audio playback and capture. Example - Documentation - Supported Platforms - Backends - Major Features - Building - Unofficia

David Reid 2.6k Jan 8, 2023
a library for audio and music analysis

aubio is a library to label music and sounds. It listens to audio signals and attempts to detect events. For instance, when a drum is hit, at which frequency is a note, or at what tempo is a rhythmic melody.

aubio 2.9k Jan 2, 2023
Single file C library for decoding MPEG1 Video and MP2 Audio

PL_MPEG - MPEG1 Video decoder, MP2 Audio decoder, MPEG-PS demuxer Single-file MIT licensed library for C/C++ See pl_mpeg.h for the documentation. Why?

Dominic Szablewski 605 Dec 27, 2022
C library for audio noise reduction and other spectral effects

libspecbleach C library for audio noise reduction and other spectral effects Background This library is based on the algorithms that were used in nois

Luciano Dato 43 Dec 15, 2022
A very simple example showing how to play mp3 files on the ESP32

ESP32 MP3 Player This repo contains a simple demonstration of how to play an MP3 file on the ESP32. You can configure the output to be either an I2S d

atomic14 38 Dec 23, 2022
C++17 library for creating macOS Audio Server plugins.

libASPL Synopsis Instructions Versioning API reference Example driver Quick start Object model Types of setters Customization Thread and realtime safe

Victor Gaydov 36 Dec 19, 2022
A discord audio playback library in c++ with node bindings

Tokio This project is still WIP. C++ Discord library with node bindings focused on audio playback. The Core parts as networking with discord/audio dec

Liz3 2 Nov 17, 2021