Convert Figma logo to code with AI

andrewrk logolibsoundio

C library for cross-platform real-time audio input and output

1,922
229
1,922
125

Top Related Projects

Audio playback and capture library written in C, in a single source file.

OpenAL Soft is a software implementation of the OpenAL 3D audio API.

A C library for reading and writing sound files containing sampled audio data.

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

1,015

The Synthesis ToolKit in C++ (STK) is a set of open source audio signal processing and algorithmic synthesis classes written in the C++ programming language.

Quick Overview

libsoundio is a lightweight, cross-platform audio input and output library written in C. It provides a simple and consistent API for working with audio devices across different operating systems, including Windows, macOS, and Linux. The library aims to be easy to use while still offering low-latency performance for real-time audio applications.

Pros

  • Cross-platform compatibility (Windows, macOS, Linux)
  • Low-latency audio input and output
  • Simple and consistent API
  • Supports various backend audio systems (WASAPI, CoreAudio, ALSA, PulseAudio, JACK)

Cons

  • Limited advanced audio processing features
  • Smaller community compared to some other audio libraries
  • Documentation could be more comprehensive
  • Fewer high-level abstractions for complex audio tasks

Code Examples

  1. Initializing the library and listing audio devices:
#include <soundio/soundio.h>
#include <stdio.h>

int main() {
    struct SoundIo *soundio = soundio_create();
    soundio_connect(soundio);

    int input_count = soundio_input_device_count(soundio);
    int output_count = soundio_output_device_count(soundio);

    printf("Input devices: %d\n", input_count);
    printf("Output devices: %d\n", output_count);

    soundio_destroy(soundio);
    return 0;
}
  1. Opening an output stream and writing audio data:
static void write_callback(struct SoundIoOutStream *outstream, int frame_count_min, int frame_count_max) {
    struct SoundIoChannelArea *areas;
    int frames_left = frame_count_max;
    int err;

    while (frames_left > 0) {
        int frame_count = frames_left;
        if ((err = soundio_outstream_begin_write(outstream, &areas, &frame_count))) {
            fprintf(stderr, "Error writing: %s\n", soundio_strerror(err));
            exit(1);
        }

        if (!frame_count)
            break;

        // Write audio data to areas
        // ...

        if ((err = soundio_outstream_end_write(outstream))) {
            fprintf(stderr, "Error writing: %s\n", soundio_strerror(err));
            exit(1);
        }

        frames_left -= frame_count;
    }
}
  1. Setting up an input stream for recording:
static void read_callback(struct SoundIoInStream *instream, int frame_count_min, int frame_count_max) {
    struct SoundIoChannelArea *areas;
    int frames_left = frame_count_max;
    int err;

    while (frames_left > 0) {
        int frame_count = frames_left;
        if ((err = soundio_instream_begin_read(instream, &areas, &frame_count))) {
            fprintf(stderr, "Error reading: %s\n", soundio_strerror(err));
            exit(1);
        }

        if (!frame_count)
            break;

        // Process audio data from areas
        // ...

        if ((err = soundio_instream_end_read(instream))) {
            fprintf(stderr, "Error reading: %s\n", soundio_strerror(err));
            exit(1);
        }

        frames_left -= frame_count;
    }
}

Getting Started

To use libsoundio in your project:

  1. Clone the repository: git clone https://github.com/andrewrk/libsoundio.git
  2. Build the library:
    cd libsoundio
    mkdir build && cd build
    cmake ..
    make
    
  3. Include the header in your C file: #include <soundio/soundio.h>
  4. Link against the library when compiling: gcc -o your_program your_program.c -lsoundio

For more detailed usage instructions and API documentation, refer to the project's README an

Competitor Comparisons

Audio playback and capture library written in C, in a single source file.

Pros of miniaudio

  • Single-file library, making integration easier
  • Supports a wider range of platforms, including mobile and web
  • More feature-rich, including audio format conversion and effects processing

Cons of miniaudio

  • Larger codebase, potentially more complex to understand and maintain
  • May have higher memory footprint due to additional features
  • Less focused on low-latency performance compared to libsoundio

Code Comparison

miniaudio:

#define MINIAUDIO_IMPLEMENTATION
#include "miniaudio.h"

ma_result result;
ma_engine engine;
result = ma_engine_init(NULL, &engine);
ma_engine_play_sound(&engine, "sound.wav", NULL);

libsoundio:

#include <soundio/soundio.h>

struct SoundIo *soundio = soundio_create();
soundio_connect(soundio);
struct SoundIoDevice *device = soundio_get_output_device(soundio, default_out_device_index);
struct SoundIoOutStream *outstream = soundio_outstream_create(device);

Both libraries provide audio playback capabilities, but miniaudio offers a more straightforward API for simple use cases. libsoundio focuses on providing low-level access to audio devices with minimal abstraction, which can be beneficial for applications requiring fine-grained control over audio processing.

OpenAL Soft is a software implementation of the OpenAL 3D audio API.

Pros of OpenAL Soft

  • More mature and widely adopted, with extensive documentation and community support
  • Offers a higher-level API, simplifying audio programming for developers
  • Provides cross-platform 3D audio capabilities out of the box

Cons of OpenAL Soft

  • Larger codebase and potentially higher resource usage
  • Less flexible for low-level audio manipulation compared to libsoundio
  • May have slightly higher latency due to its abstraction layer

Code Comparison

OpenAL Soft:

ALCdevice *device = alcOpenDevice(NULL);
ALCcontext *context = alcCreateContext(device, NULL);
alcMakeContextCurrent(context);

alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
alSourcePlay(source);

libsoundio:

struct SoundIo *soundio = soundio_create();
soundio_connect(soundio);
struct SoundIoDevice *device = soundio_get_output_device(soundio, default_out_device_index);
struct SoundIoOutStream *outstream = soundio_outstream_create(device);
soundio_outstream_open(outstream);
soundio_outstream_start(outstream);

OpenAL Soft provides a higher-level API for audio playback, while libsoundio offers more direct control over audio streams. OpenAL Soft is better suited for 3D audio and game development, whereas libsoundio is more appropriate for low-latency audio applications and custom audio processing.

A C library for reading and writing sound files containing sampled audio data.

Pros of libsndfile

  • Supports a wide range of audio file formats (WAV, AIFF, AU, RAW, PAF, SVX, NIST, VOC, IRCAM, W64, MAT4, MAT5, PVF, XI, HTK, SDS, AVR, WAVEX, SD2, CAF, WVE, MPC2K, RF64)
  • Provides high-level API for reading, writing, and manipulating audio files
  • Well-established and widely used in audio processing applications

Cons of libsndfile

  • Focuses primarily on file I/O, not real-time audio processing
  • May have higher overhead for simple audio tasks compared to libsoundio
  • Less emphasis on cross-platform audio device handling

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);

libsoundio:

#include <soundio/soundio.h>

struct SoundIo *soundio = soundio_create();
soundio_connect(soundio);
struct SoundIoDevice *device = soundio_get_input_device(soundio, device_index);
struct SoundIoInStream *instream = soundio_instream_create(device);
soundio_instream_open(instream);

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

Pros of PortAudio

  • Mature and widely adopted, with extensive documentation and community support
  • Cross-platform compatibility, supporting a wide range of operating systems and audio APIs
  • Offers both callback-based and blocking I/O models for flexibility

Cons of PortAudio

  • More complex API compared to libsoundio, which can lead to a steeper learning curve
  • Older codebase with some legacy design decisions that may not align with modern C programming practices
  • Larger footprint and potentially slower performance in some scenarios

Code Comparison

PortAudio example:

PaStream *stream;
PaError err = Pa_OpenDefaultStream(&stream, 2, 2, paFloat32, 44100, 256, NULL, NULL);
if (err != paNoError) {
    // Handle error
}

libsoundio example:

struct SoundIoOutStream *outstream = soundio_outstream_create(device);
outstream->format = SoundIoFormatFloat32NE;
outstream->sample_rate = 44100;
int err = soundio_outstream_open(outstream);
if (err) {
    // Handle error
}

Both libraries provide similar functionality for opening audio streams, but libsoundio's API is generally more straightforward and modern. PortAudio offers more options and flexibility, which can be beneficial for complex audio applications but may introduce additional complexity for simpler use cases.

1,015

The Synthesis ToolKit in C++ (STK) is a set of open source audio signal processing and algorithmic synthesis classes written in the C++ programming language.

Pros of STK

  • Comprehensive toolkit for audio signal processing and synthesis
  • Includes a wide range of musical instrument models and algorithms
  • Supports MIDI input and output

Cons of STK

  • Less focused on low-latency audio I/O compared to libsoundio
  • May have a steeper learning curve due to its broader scope
  • Not as actively maintained as libsoundio

Code Comparison

STK example (simple sine wave synthesis):

#include "SineWave.h"
#include "RtAudio.h"

StkFloat tick(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames) {
    SineWave sine;
    return sine.tick();
}

libsoundio example (simple audio output):

#include <soundio/soundio.h>

static void write_callback(struct SoundIoOutStream *outstream, int frame_count_min, int frame_count_max) {
    struct SoundIoChannelArea *areas;
    int frames_left = frame_count_max;
    int err;

    while (frames_left > 0) {
        int frame_count = frames_left;
        if ((err = soundio_outstream_begin_write(outstream, &areas, &frame_count)))
            exit(1);
        // Write audio data here
        if ((err = soundio_outstream_end_write(outstream)))
            exit(1);
        frames_left -= frame_count;
    }
}

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

libsoundio

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

This library is an abstraction; however in the delicate balance between performance and power, and API convenience, the scale is tipped closer to the former. Features that only exist in some sound backends are exposed.

Features and Limitations

  • Supported operating systems:
    • Windows 7+
    • MacOS 10.10+
    • Linux 3.7+
  • Supported backends:
  • Exposes both raw devices and shared devices. Raw devices give you the best performance but prevent other applications from using them. Shared devices are default and usually provide sample rate conversion and format conversion.
  • Exposes both device id and friendly name. id you could save in a config file because it persists between devices becoming plugged and unplugged, while friendly name is suitable for exposing to users.
  • Supports optimal usage of each supported backend. The same API does the right thing whether the backend has a fixed buffer size, such as on JACK and CoreAudio, or whether it allows directly managing the buffer, such as on ALSA, PulseAudio, and WASAPI.
  • C library. Depends only on the respective backend API libraries and libc. Does not depend on libstdc++, and does not have exceptions, run-time type information, or setjmp.
  • Errors are communicated via return codes, not logging to stdio.
  • Supports channel layouts (also known as channel maps), important for surround sound applications.
  • Ability to monitor devices and get an event when available devices change.
  • Ability to get an event when the backend is disconnected, for example when the JACK server or PulseAudio server shuts down.
  • Detects which input device is default and which output device is default.
  • Ability to connect to multiple backends at once. For example you could have an ALSA device open and a JACK device open at the same time.
  • Meticulously checks all return codes and memory allocations and uses meaningful error codes.
  • Exposes extra API that is only available on some backends. For example you can provide application name and stream names which is used by JACK and PulseAudio.

Synopsis

Complete program to emit a sine wave over the default device using the best backend:

#include <soundio/soundio.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

static const float PI = 3.1415926535f;
static float seconds_offset = 0.0f;
static void write_callback(struct SoundIoOutStream *outstream,
        int frame_count_min, int frame_count_max)
{
    const struct SoundIoChannelLayout *layout = &outstream->layout;
    float float_sample_rate = outstream->sample_rate;
    float seconds_per_frame = 1.0f / float_sample_rate;
    struct SoundIoChannelArea *areas;
    int frames_left = frame_count_max;
    int err;

    while (frames_left > 0) {
        int frame_count = frames_left;

        if ((err = soundio_outstream_begin_write(outstream, &areas, &frame_count))) {
            fprintf(stderr, "%s\n", soundio_strerror(err));
            exit(1);
        }

        if (!frame_count)
            break;

        float pitch = 440.0f;
        float radians_per_second = pitch * 2.0f * PI;
        for (int frame = 0; frame < frame_count; frame += 1) {
            float sample = sinf((seconds_offset + frame * seconds_per_frame) * radians_per_second);
            for (int channel = 0; channel < layout->channel_count; channel += 1) {
                float *ptr = (float*)(areas[channel].ptr + areas[channel].step * frame);
                *ptr = sample;
            }
        }
        seconds_offset = fmodf(seconds_offset +
            seconds_per_frame * frame_count, 1.0f);

        if ((err = soundio_outstream_end_write(outstream))) {
            fprintf(stderr, "%s\n", soundio_strerror(err));
            exit(1);
        }

        frames_left -= frame_count;
    }
}

int main(int argc, char **argv) {
    int err;
    struct SoundIo *soundio = soundio_create();
    if (!soundio) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    if ((err = soundio_connect(soundio))) {
        fprintf(stderr, "error connecting: %s", soundio_strerror(err));
        return 1;
    }

    soundio_flush_events(soundio);

    int default_out_device_index = soundio_default_output_device_index(soundio);
    if (default_out_device_index < 0) {
        fprintf(stderr, "no output device found");
        return 1;
    }

    struct SoundIoDevice *device = soundio_get_output_device(soundio, default_out_device_index);
    if (!device) {
        fprintf(stderr, "out of memory");
        return 1;
    }

    fprintf(stderr, "Output device: %s\n", device->name);

    struct SoundIoOutStream *outstream = soundio_outstream_create(device);
    outstream->format = SoundIoFormatFloat32NE;
    outstream->write_callback = write_callback;

    if ((err = soundio_outstream_open(outstream))) {
        fprintf(stderr, "unable to open device: %s", soundio_strerror(err));
        return 1;
    }

    if (outstream->layout_error)
        fprintf(stderr, "unable to set channel layout: %s\n", soundio_strerror(outstream->layout_error));

    if ((err = soundio_outstream_start(outstream))) {
        fprintf(stderr, "unable to start device: %s", soundio_strerror(err));
        return 1;
    }

    for (;;)
        soundio_wait_events(soundio);

    soundio_outstream_destroy(outstream);
    soundio_device_unref(device);
    soundio_destroy(soundio);
    return 0;
}

Backend Priority

When you use soundio_connect, libsoundio tries these backends in order. If unable to connect to that backend, due to the backend not being installed, or the server not running, or the platform is wrong, the next backend is tried.

  1. JACK
  2. PulseAudio
  3. ALSA (Linux)
  4. CoreAudio (OSX)
  5. WASAPI (Windows)
  6. Dummy

If you don't like this order, you can use soundio_connect_backend to explicitly choose a backend to connect to. You can use soundio_backend_count and soundio_get_backend to get the list of available backends.

API Documentation

Building

Install the dependencies:

  • cmake
  • ALSA library (optional)
  • libjack2 (optional)
  • libpulseaudio (optional)
mkdir build
cd build
cmake ..
make
sudo make install

Building for Windows

You can build libsoundio with mxe. Follow the requirements section to install the packages necessary on your system. Then somewhere on your file system:

git clone https://github.com/mxe/mxe
cd mxe
make MXE_TARGETS='x86_64-w64-mingw32.static i686-w64-mingw32.static' gcc

Then in the libsoundio source directory (replace "/path/to/mxe" with the appropriate path):

mkdir build-win32
cd build-win32
cmake .. -DCMAKE_TOOLCHAIN_FILE=/path/to/mxe/usr/i686-w64-mingw32.static/share/cmake/mxe-conf.cmake
make
mkdir build-win64
cd build-win64
cmake .. -DCMAKE_TOOLCHAIN_FILE=/path/to/mxe/usr/x86_64-w64-mingw32.static/share/cmake/mxe-conf.cmake
make

Testing

For each backend, do the following:

  1. Run the unit tests: ./unit_tests. To see test coverage, install lcov, run make coverage, and then view coverage/index.html in a browser.
  2. Run the example ./sio_list_devices and make sure it does not crash, and the output looks good. If valgrind is available, use it.
  3. Run ./sio_list_devices --watch and make sure it detects when you plug and unplug a USB microphone.
  4. Run ./sio_sine and make sure you hear a sine wave. For backends with raw devices, run ./sio_sine --device id --raw (where 'id' is a device id you got from sio_list_devices and make sure you hear a sine wave.
    • Use 'p' to test pausing, 'u' to test unpausing, 'q' to test cleanup.
    • 'c' for clear buffer. Clear buffer should not pause the stream and it should also not cause an underflow.
    • Use 'P' to test pausing from the callback, and then 'u' to unpause.
  5. Run ./underflow and read the testing instructions that it prints.
  6. Run ./sio_microphone and ensure that it is both recording and playing back correctly. If possible use the --in-device and --out-device parameters to test a USB microphone in raw mode.
  7. Run ./backend_disconnect_recover and read the testing instructions that it prints.
  8. Run ./latency and make sure the printed beeps line up with the beeps that you hear.

Building the Documentation

Ensure that doxygen is installed, then:

make doc

Then look at html/index.html in a browser.