1. Products
  2.   Audio
  3.   C++
  4.   portaudio

portaudio

 
 

Open Source C Library for Audio I/O

Real-Time Audio Input & Output Across Windows, macOS, Linux, and More via Open Source C API.

What is portaudio?

PortAudio is a free, open-source, cross-platform C library that enables developers to write portable audio applications with real-time input and output capabilities. It abstracts platform-specific audio subsystems like ASIO, CoreAudio, ALSA, WASAPI, and JACK, allowing consistent audio I/O across Windows, macOS, Linux, and other operating systems. The library supports multiple audio formats—including 32-bit floating point—and handles format conversion internally. With a simple yet powerful API, PortAudio is widely used in audio software, plugins, educational tools, and research projects requiring low-latency, high-performance audio processing.

PortAudio provides two primary modes of operation: callback-based (for low-latency streaming) and blocking read/write (for simpler synchronous I/O). It includes extensive documentation, example programs, and test utilities to help developers get started quickly. The library is maintained by a global community and is licensed under the MIT license, making it suitable for both open-source and commercial applications. Whether you're building a digital audio workstation, a voice recognition tool, or an interactive music application, PortAudio delivers a reliable, lightweight foundation for cross-platform audio development.

Previous Next

Getting Started with portaudio

To begin using PortAudio, you can either build it from source or install via package managers. For most developers, the easiest method is to clone the official portaudio GitHub repository and compile using CMake or autotools. On Linux, install via `apt install portaudio19-dev`; on macOS, use `brew install portaudio`; on Windows, download prebuilt binaries or use vcpkg (`vcpkg install portaudio`). After installation, include `portaudio.h` and link against the library (`-lportaudio`). The library is lightweight and has minimal dependencies, making integration straightforward for real-time audio applications.

Install PortAudio via Package Managers

# Linux (Debian/Ubuntu)
sudo apt install portaudio19-dev

# macOS (Homebrew)
brew install portaudio

# Windows (vcpkg)
vcpkg install portaudio

Real-Time Audio Streaming with Callbacks

PortAudio’s callback-based streaming mode is ideal for low-latency, real-time audio processing. When a stream is started, PortAudio periodically invokes your callback function to request or supply audio data. This mode gives you precise control over timing and minimizes buffer underruns. The callback receives input and output buffers, frame count, time info, and status flags—enabling dynamic audio generation, effects processing, or analysis. Since the callback runs in a high-priority thread, it must execute quickly (typically under 10ms) to avoid glitches. This makes it perfect for live audio applications like synthesizers, guitar effects pedals, or voice communication systems where deterministic performance is critical.

Real-Time Sine Wave Generator via Callback

typedef struct {
    float phase;
    float phase_increment;
} paTestData;

int patestCallback(const void *input, void *output,
    unsigned long frameCount,
    const PaStreamCallbackTimeInfo* timeInfo,
    PaStreamCallbackFlags statusFlags,
    void *userData)
{
    paTestData *data = (paTestData*)userData;
    float *out = (float*)output;
    for (unsigned long i = 0; i < frameCount; i++) {
        *out++ = sinf(data->phase);
        data->phase += data->phase_increment;
        if (data->phase >= M_PI * 2) data->phase -= M_PI * 2;
    }
    return paContinue;
}

Device Enumeration and Querying

PortAudio provides robust APIs to enumerate and inspect available audio devices—including input and output devices—along with their capabilities. Developers can query device names, channel counts, default sample rates, and latency values using functions like `Pa_GetDeviceCount()`, `Pa_GetDeviceInfo()`, and `Pa_GetDefaultInputDeviceID()`. This allows applications to present users with a list of valid devices and configure streams optimally. You can also detect default devices, check supported sample rates, and determine minimum/maximum latencies. This flexibility is essential for building configurable audio tools, DAWs, or voice recorders that adapt to diverse hardware setups without manual configuration.

List All Available Audio Devices

PaError err;
err = Pa_Initialize();
if (err != paNoError) goto error;

int numDevices = Pa_GetDeviceCount();
for (int i = 0; i < numDevices; i++) {
    const PaDeviceInfo *info = Pa_GetDeviceInfo(i);
    printf("%d: %s (in: %d, out: %d)\n", 
        i, info->name, 
        info->maxInputChannels, 
        info->maxOutputChannels);
}
Pa_Terminate();

Cross-Platform Host API Support

PortAudio abstracts platform-specific audio APIs through modular host API implementations, ensuring consistent behavior across operating systems. On Windows, it supports ASIO (for pro audio), WASAPI (Vista+), DirectSound, and legacy MME. macOS leverages Core Audio for ultra-low latency, while Linux supports ALSA, JACK, and PulseAudio. BSD systems use OSS or sndio. Developers write once and deploy everywhere—no conditional compilation needed for core logic. The library automatically selects the best available host API or lets you specify one explicitly. This universality makes PortAudio ideal for portable audio tools, educational software, and research frameworks that must run reliably on diverse hardware and OS configurations.

Force Use of JACK Host API on Linux

PaStreamParameters inputParam, outputParam;
PaError err;

inputParam.device = Pa_GetHostApiInfoByType(paJACK)->defaultInputDevice;
inputParam.channelCount = 2;
inputParam.sampleFormat = paFloat32;
// ... configure outputParam similarly ...

PaStream *stream;
err = Pa_OpenStream(&stream, &inputParam, &outputParam, 
    44100, 256, paNoFlag, callback, NULL);

Audio Format Conversion and Dithering

PortAudio handles internal sample format conversion transparently, allowing clients to use convenient formats like 32-bit floating point while the underlying system uses native integer formats (e.g., 16-bit PCM). It supports conversion between 8-, 16-, 24-, and 32-bit integer formats, as well as 32-bit float. Additionally, it offers optional dithering during bit-depth reduction to minimize quantization noise—a subtle but critical feature for high-fidelity audio applications. Dithering preserves perceived audio quality when converting from higher to lower bit depths. These capabilities ensure consistent audio fidelity across platforms without requiring developers to implement complex format-handling logic themselves.

Configure 32-bit Float Input with Dithering

PaStreamParameters inputParam = {0};
inputParam.device = Pa_GetDefaultInputDevice();
inputParam.channelCount = 2;
inputParam.sampleFormat = paFloat32;
inputParam.suggestedLatency = Pa_GetDeviceInfo(inputParam.device)->defaultLowInputLatency;

// Enable dithering for output conversion
PaStream *stream;
Pa_OpenStream(&stream, &inputParam, NULL, 44100, 128, 
    paClipOff | paDitherOff, NULL, NULL);
// Note: paDitherOff disables dithering; omit for default dithering