libsndfile
A C library for reading and writing sound files containing sampled audio data.
Top Related Projects
Quick Overview
Libsndfile is a C library for reading and writing files containing sampled sound (such as MS Windows WAV files, Apple/SGI AIFF files, Sun/NeXT AU files, and others). It is widely used in audio processing applications and supports a variety of audio file formats.
Pros
- Supports a wide range of audio file formats
- Cross-platform compatibility (Windows, macOS, Linux)
- Provides a simple and consistent API for handling different audio file types
- Actively maintained with regular updates and bug fixes
Cons
- Limited to file I/O operations, not designed for real-time audio processing
- Requires some understanding of audio concepts for effective use
- May have a steeper learning curve for beginners compared to higher-level audio libraries
- Documentation could be more comprehensive for advanced use cases
Code Examples
Reading an audio file:
#include <sndfile.h>
SNDFILE *file;
SF_INFO sfinfo;
sf_count_t num_frames;
file = sf_open("input.wav", SFM_READ, &sfinfo);
if (!file) {
printf("Error opening file: %s\n", sf_strerror(file));
return 1;
}
num_frames = sf_readf_float(file, buffer, BUFFER_LEN);
sf_close(file);
Writing an audio file:
#include <sndfile.h>
SNDFILE *file;
SF_INFO sfinfo;
sfinfo.samplerate = 44100;
sfinfo.channels = 2;
sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
file = sf_open("output.wav", SFM_WRITE, &sfinfo);
if (!file) {
printf("Error opening file for writing: %s\n", sf_strerror(file));
return 1;
}
sf_writef_float(file, buffer, num_frames);
sf_close(file);
Getting file information:
#include <sndfile.h>
SNDFILE *file;
SF_INFO sfinfo;
file = sf_open("input.wav", SFM_READ, &sfinfo);
if (!file) {
printf("Error opening file: %s\n", sf_strerror(file));
return 1;
}
printf("Channels: %d\n", sfinfo.channels);
printf("Sample rate: %d\n", sfinfo.samplerate);
printf("Format: %d\n", sfinfo.format);
sf_close(file);
Getting Started
-
Install libsndfile:
- On Ubuntu/Debian:
sudo apt-get install libsndfile1-dev
- On macOS with Homebrew:
brew install libsndfile
- On Windows, download pre-built binaries or build from source
- On Ubuntu/Debian:
-
Include the header in your C/C++ file:
#include <sndfile.h>
-
Compile your program with libsndfile:
gcc -o myprogram myprogram.c -lsndfile
-
Start using libsndfile functions in your code, such as
sf_open()
,sf_read_float()
, andsf_close()
.
Competitor Comparisons
Free Lossless Audio Codec
Pros of FLAC
- Specialized for lossless audio compression, offering better compression ratios for FLAC files
- Includes a reference encoder and decoder implementation
- Supports metadata tags and album art embedding
Cons of FLAC
- Limited to FLAC format only, while libsndfile supports multiple audio formats
- Less suitable for general-purpose audio file handling and manipulation
- May require additional libraries for handling other audio formats
Code Comparison
FLAC (encoding example):
FLAC__StreamEncoder *encoder = FLAC__stream_encoder_new();
FLAC__stream_encoder_set_channels(encoder, channels);
FLAC__stream_encoder_set_bits_per_sample(encoder, bits_per_sample);
FLAC__stream_encoder_init_file(encoder, output_file, NULL, NULL);
FLAC__stream_encoder_process_interleaved(encoder, buffer, samples);
libsndfile (writing example):
SF_INFO sfinfo;
sfinfo.channels = channels;
sfinfo.samplerate = sample_rate;
sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
SNDFILE *file = sf_open(output_file, SFM_WRITE, &sfinfo);
sf_write_float(file, buffer, frames * channels);
Both libraries offer C APIs for audio file handling, but FLAC focuses on its specific format while libsndfile provides a more general-purpose interface for various audio formats.
TagLib Audio Meta-Data Library
Pros of TagLib
- Focuses on reading and writing metadata tags for various audio formats
- Supports a wider range of metadata formats (ID3v1, ID3v2, APE, FLAC, etc.)
- Provides a high-level, easy-to-use API for metadata manipulation
Cons of TagLib
- Limited audio decoding capabilities compared to libsndfile
- Primarily designed for metadata handling, not audio processing
- May have a steeper learning curve for basic audio file operations
Code Comparison
TagLib (reading metadata):
#include <taglib/fileref.h>
#include <taglib/tag.h>
TagLib::FileRef f("song.mp3");
TagLib::String title = f.tag()->title();
int year = f.tag()->year();
libsndfile (reading audio data):
#include <sndfile.h>
SNDFILE *file;
SF_INFO sfinfo;
file = sf_open("audio.wav", SFM_READ, &sfinfo);
sf_count_t frames_read = sf_readf_float(file, buffer, num_frames);
Both libraries serve different primary purposes: TagLib excels in metadata handling, while libsndfile focuses on audio file I/O and processing. TagLib is more suitable for applications that require extensive metadata manipulation, whereas libsndfile is better for audio signal processing and format conversion tasks.
Audio decoding libraries for C/C++, each in a single source file.
Pros of dr_libs
- Single-file, header-only libraries for easy integration
- Supports a wider range of audio formats, including MP3 and FLAC
- Lightweight and minimal dependencies
Cons of dr_libs
- Less mature and potentially less stable than libsndfile
- May lack some advanced features and optimizations present in libsndfile
- Limited documentation compared to libsndfile
Code Comparison
libsndfile:
#include <sndfile.h>
SNDFILE *file;
SF_INFO sfinfo;
file = sf_open("audio.wav", SFM_READ, &sfinfo);
sf_read_float(file, buffer, frames);
sf_close(file);
dr_libs:
#define DR_WAV_IMPLEMENTATION
#include "dr_wav.h"
drwav wav;
drwav_init_file(&wav, "audio.wav", NULL);
drwav_read_pcm_frames_f32(&wav, frames, buffer);
drwav_uninit(&wav);
Both libraries provide simple APIs for reading audio files, but dr_libs uses a more compact, header-only approach. libsndfile offers a more traditional library structure with separate compilation and linking steps.
Mirror of https://git.ffmpeg.org/ffmpeg.git
Pros of FFmpeg
- Broader functionality: Handles video and audio processing, transcoding, and streaming
- Extensive codec support: Works with a vast array of audio and video formats
- Active development: Frequent updates and large community support
Cons of FFmpeg
- Steeper learning curve: More complex to use due to its extensive feature set
- Larger footprint: Requires more system resources and storage space
- Potential overkill: May be excessive for projects focused solely on audio processing
Code Comparison
FFmpeg (audio conversion):
ffmpeg -i input.wav -acodec libmp3lame -b:a 128k output.mp3
libsndfile (audio reading):
#include <sndfile.h>
SNDFILE *file;
SF_INFO sfinfo;
file = sf_open("input.wav", SFM_READ, &sfinfo);
Key Differences
- Scope: FFmpeg is a comprehensive multimedia framework, while libsndfile focuses on reading and writing audio files
- Use case: FFmpeg is ideal for complex multimedia projects, libsndfile for audio-specific applications
- API: FFmpeg offers command-line and programmatic interfaces, libsndfile provides a C library for direct integration
Conclusion
Choose FFmpeg for versatile multimedia processing, or libsndfile for lightweight, audio-specific tasks. Consider project requirements, performance needs, and development complexity when selecting between these libraries.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
libsndfile
libsndfile is a C library for reading and writing files containing sampled audio data.
Authors
The libsndfile project was originally developed and maintained by Erik de Castro Lopo erikd@mega-nerd.com aka @erikd. The project was developed on Github at https://github.com/erikd/libsndfile.
After the release of version 1.0.30, @erikd transferred the project to the libsndfile team, see AUTHORS for details.
Hacking
The canonical source code repository for libsndfile is at https://github.com/libsndfile/libsndfile.
You can grab the source code using:
git clone https://github.com/libsndfile/libsndfile.git
For building for Android see BuildingForAndroid.
There are currently two build systems: the traditional GNU autotool based one and modern CMake based build system. Use of the CMake build system is documented below.
Setting up a build environment for libsndfile on Debian or Ubuntu is as simple as:
sudo apt install autoconf autogen automake build-essential libasound2-dev \
libflac-dev libogg-dev libtool libvorbis-dev libopus-dev libmp3lame-dev \
libmpg123-dev pkg-config python
For other Linux distributions or any of the *BSDs, the setup should be similar although the package install tools and package names may be slightly different.
Similarly on Mac OS X, assuming brew is already installed:
brew install autoconf autogen automake flac libogg libtool libvorbis opus mpg123 pkg-config
Once the build environment has been set up, building and testing libsndfile is as simple as:
autoreconf -vif
./configure --enable-werror
make
make check
The CMake build system
Although Autotools is the primary and recommended build toolchain, CMake meta build generator is also available. The build process with CMake takes place in two stages. First, standard build files are created from configuration scripts. Then the platform's native build tools are used for the actual building. CMake can produce Microsoft Visual Studio project and solution files, Unix Makefiles, Xcode projects and many more.
Some IDE support CMake natively or with plugins, check you IDE documentation for details.
Requirements
- C99-compliant compiler toolchain (tested with GCC, Clang and Visual Studio 2015)
- CMake 3.1.3 or newer
There are some recommended packages to enable all features of libsndfile:
- Ogg, Vorbis and FLAC libraries and headers to enable these formats support
- ALSA development package under Linux to build sndfile-play utility
- Sndio development package under BSD to build sndfile-play utility
Building from command line
CMake can handle out-of-place builds, enabling several builds from the same source tree, and cross-compilation. The ability to build a directory tree outside the source tree is a key feature, ensuring that if a build directory is removed, the source files remain unaffected.
mkdir CMakeBuild
cd CMakeBuild
Then run cmake
command with directory where CMakeLists.txt script is located
as argument (relative paths are supported):
cmake ..
This command will configure and write build script or solution to CMakeBuild
directory. CMake is smart enough to create Unix makefiles under Linux or Visual
Studio solution if you have Visual Studio installed, but you can configure
generator
with -G
command line parameter:
cmake .. -G"Unix Makefiles"
The build procedure depends on the selected generator. With "Unix Makefiles" you can type:
make & make install
With "Visual Studio" and some other generators you can open solution or project
from CMakeBuild
directory and build using IDE.
Finally, you can use unified command:
cmake --build .
CMake also provides Qt-based cross platform GUI, cmake-gui. Using it is trivial and does not require detailed explanations.
Configuring CMake
You can pass additional options with /D<parameter>=<value>
when you run
cmake
command. Some useful system options:
CMAKE_C_FLAGS
- additional C compiler flagsCMAKE_BUILD_TYPE
- configuration type,DEBUG
,RELEASE
,RELWITHDEBINFO
orMINSIZEREL
.DEBUG
is defaultCMAKE_INSTALL_PREFIX
- build install location, the same as--prefix
option ofconfigure
script
Useful libsndfile options:
-
BUILD_SHARED_LIBS
- build shared library (DLL under Windows) whenON
, build static library otherwise. This option isOFF
by default. -
BUILD_PROGRAMS
- build libsndfile's utilities fromprograms/
directory,ON
by default. -
BUILD_EXAMPLES
- build examples,ON
by default. -
BUILD_TESTING
- build tests. Then you can run tests withctest
command,ON
by default. SettingBUILD_SHARED_LIBS
toON
disables this option. -
ENABLE_EXTERNAL_LIBS
- enable Ogg, Vorbis, FLAC and Opus support. This option is available and set toON
if all dependency libraries were found. -
ENABLE_MPEG
- MP3 support. This option is available and set toON
if all dependency libraries were found. -
ENABLE_BOW_DOCS
- enable black-on-white documentation theme,OFF
by default. -
ENABLE_EXPERIMENTAL
- enable experimental code. Don't use it if you are not sure. This option isOFF
by default. -
ENABLE_CPACK
- enable CPack support. This option isON
by default. -
ENABLE_PACKAGE_CONFIG
- generate and install package config file. -
INSTALL_PKGCONFIG_MODULE
- generate and install pkg-config module. -
INSTALL_MANPAGES
- install man pages for programs. This option isON
by default -
ENABLE_STATIC_RUNTIME
- enable static runtime on Windows platform (MSVC and MinGW),OFF
by default.Note: For MSVC compiler this option is deprecated for CMake >= 3.15, see policy CMP0091. Use
CMAKE_MSVC_RUNTIME_LIBRARY
option instead.Note: For MinGW toolchain this option is experimental. If you enabled it and then disabled again, you need to clear CMake cache (delete CMakeCache.txt).
-
ENABLE_COMPATIBLE_LIBSNDFILE_NAME
- set DLL name tolibsndfile-1.dll
(canonical name) on Windows platform,sndfile.dll
otherwise,OFF
by default. Library name can be different depending on platform. The well known DLL name on Windows platform islibsndfile-1.dll
, because the only way to build Windows library before was MinGW toolchain with Autotools. This name is native for MinGW ecosystem, Autotools constructs it using MinGW platform rules fromsndfile
target. But when you build with CMake using native Windows compiler, the name issndfile.dll
. This is name for native Windows platform, because Windows has no library naming rules. It is preferred because you can search library using package manager or CMake'sfind_library
command on any platform using the samesndfile
name. -
ENABLE_SSE2
- add compiler flag to enable SSE2 if required,ON
by default.This option is for X86 and GCC compatible compilers configurations only.
If you compile for other SIMD set, e.g. AVX2, you may want to set
ENABLE_SSE2
toOFF
.Note: This option is not active for X64 configuration, because SSE2 is always available in this mode and all optimizations are enabled by default.
Deprecated options:
DISABLE_EXTERNAL_LIBS
- disable Ogg, Vorbis and FLAC support. Replaced byENABLE_EXTERNAL_LIBS
BUILD_STATIC_LIBS
- build static library. UseBUILD_SHARED_LIBS
instead
Linking from CMake projects
First you need to add FindOgg.cmake
, FindVorbis.cmake
, FindFLAC.cmake
and
FindOpus.cmake
files to some directory inside your CMake project (usually
cmake
) and add it to CMAKE_MODULE_PATH
:
project(SomeApplication)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
Now you can search libsndfile
library from your CMakeLists.txt
with this command:
find_package(SndFile)
SndFile_FOUND
is set to ON
when library is found.
If libsndfile
dependency is critical, you can add REQUIRED
to
find_package
:
find_package(SndFile REQUIRED)
With with option find_package
will terminate configuration process
if libsndfile
is not found.
You can also add version check:
find_package(SndFile 1.0.29)
find_package
will report error, if libsndfile
version is < 1.0.29.
You can combine REQUIRED
and version if you need.
To link libsndfile
library use:
target_link_libraries(my_application PRIVATE SndFile::sndfile)
Notes for Windows users
System CRT library
First advice about Visual Studio system CRT libraries, it is system code linked as static or dynamic library to every C application.
You can find related option in Visual Studio project properties:
C/C++ -> Code Generation -> Runtime Library
Dynamic version of system CRT library is default and it means that end user needs to have the same runtime library installed on his system. Most likely it is so, but if it is not, the user will see this error message using libsndfile DLL:
"The program can't start because <crt-dll-name>.dll is missing from your computer. Try reinstalling the program to fix this problem. "
To avoid this, you may want to enable static CRT library linking. In this case the size of your DLL will increase slightly the size will increase slightly, but you can redistribute the libsndfile DLL without having to install the correct version of the system CRT library.
CMake project will use dynamic system CRT libraries by default, just like
Visual Studio does. But you can change it using ENABLE_STATIC_RUNTIME
or
CMAKE_MSVC_RUNTIME_LIBRARY
options.
Note: You cannot use both options at the same time, it will lead to a configuration error.
If you have CMake >= 3.15 you should use
CMAKE_MSVC_RUNTIME_LIBRARY
option.
This will enable static linking:
cmake .. -D"MultiThreaded$<$<CONFIG:Debug>:Debug>"
You can use libsndfile ENABLE_STATIC_RUNTIME
option to to control CRT library
linking for CMake project: OFF
or unset (default) for dynamic, and ON
for
static linking:
cmake .. -DENABLE_STATIC_RUNTIME=ON
Note: This option is deprecated and may be removed in far future because we
have standard option CMAKE_MSVC_RUNTIME_LIBRARY
now.
Using Vcpkg package manager
Second advice is about Ogg, Vorbis FLAC and Opus support. Searching external libraries under Windows is a little bit tricky. The best way is to use Vcpkg.
Install Vcpkg and then add this parameter to cmake command line:
-DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/scripts/buildsystems/vcpkg.cmake
You also need to set VCPKG_TARGET_TRIPLET
if you want to use static libraries:
-DVCPKG_TARGET_TRIPLET=x64-windows-static
Then you need to install static libogg, libvorbis, libflac, libopus, mpg123 and mp3lame Vcpkg packages.
After 1.1.0beta2 you don't need to install dependencies manually. Libsndfile now supports Vcpkg manifest mode and all dependencies are installed automatically.
However, you can turn off the manifest mode and return to the classic mode using
the VCPKG_MANIFEST_MODE
parameter from the command line:
-DVCPKG_MANIFEST_MODE=OFF
In classic mode, you need to install the required libraries manually:
vcpkg install libvorbis:x64-windows-static libflac:x64-windows-static
opus:x64-windows-static mp3lame:x86-windows-static mpg123:x86-windows-static
libvorbis:x86-windows-static libflac:x86-windows-static
opus:x86-windows-static mp3lame:x86-windows-static mpg123:x86-windows-static
Note: Use must use the same CRT library for external libraries and the
libsndfile library itself. For *-static
triplets Vcpkg uses
static CRT.
Submitting Patches
See CONTRIBUTING.md for details.
Top Related Projects
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot