[][src]Crate cpal

How to use cpal

Here are some concepts cpal exposes:

  • A Host provides access to the available audio devices on the system. Some platforms have more than one host available, but every platform supported by CPAL has at least one DefaultHost that is guaranteed to be available.
  • A Device is an audio device that may have any number of input and output streams.
  • A Stream is an open flow of audio data. Input streams allow you to receive audio data, output streams allow you to play audio data. You must choose which Device will run your stream before you can create one. Often, a default device can be retrieved via the Host.

The first step is to initialise the Host:

use cpal::traits::HostTrait;
let host = cpal::default_host();

Then choose an available Device. The easiest way is to use the default input or output Device via the default_input_device() or default_output_device() functions. Alternatively you can enumerate all the available devices with the devices() function. Beware that the default_*_device() functions return an Option in case no device is available for that stream type on the system.

let device = host.default_output_device().expect("no output device available");

Before we can create a stream, we must decide what the configuration of the audio stream is going to be. You can query all the supported configurations with the supported_input_configs() and supported_output_configs() methods. These produce a list of SupportedStreamConfigRange structs which can later be turned into actual SupportedStreamConfig structs. If you don't want to query the list of configs, you can also build your own StreamConfig manually, but doing so could lead to an error when building the stream if the config is not supported by the device.

Note: the supported_input/output_configs() methods could return an error for example if the device has been disconnected.

use cpal::traits::{DeviceTrait, HostTrait};
let mut supported_configs_range = device.supported_output_configs()
    .expect("error while querying configs");
let supported_config = supported_configs_range.next()
    .expect("no supported config?!")

Now that we have everything for the stream, we are ready to create it from our selected device:

use cpal::Data;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
let stream = device.build_output_stream(
    move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
        // react to stream events and read or write stream data here.
    move |err| {
        // react to errors here.

While the stream is running, the selected audio device will periodically call the data callback that was passed to the function. The callback is passed an instance of either &Data or &mut Data depending on whether the stream is an input stream or output stream respectively.

Note: Creating and running a stream will not block the thread. On modern platforms, the given callback is called by a dedicated, high-priority thread responsible for delivering audio data to the system's audio device in a timely manner. On older platforms that only provide a blocking API (e.g. ALSA), CPAL will create a thread in order to consistently provide non-blocking behaviour (currently this is a thread per stream, but this may change to use a single thread for all streams). If this is an issue for your platform or design, please share your issue and use-case with the CPAL team on the github issue tracker for consideration.

In this example, we simply fill the given output buffer with silence.

use cpal::{Data, Sample, SampleFormat};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
let err_fn = |err| eprintln!("an error occurred on the output audio stream: {}", err);
let sample_format = supported_config.sample_format();
let config = supported_config.into();
let stream = match sample_format {
    SampleFormat::F32 => device.build_output_stream(&config, write_silence::<f32>, err_fn),
    SampleFormat::I16 => device.build_output_stream(&config, write_silence::<i16>, err_fn),
    SampleFormat::U16 => device.build_output_stream(&config, write_silence::<u16>, err_fn),

fn write_silence<T: Sample>(data: &mut [T], _: &cpal::OutputCallbackInfo) {
    for sample in data.iter_mut() {
        *sample = Sample::from(&0.0);

Not all platforms automatically run the stream upon creation. To ensure the stream has started, we can use Stream::play.


Some devices support pausing the audio stream. This can be useful for saving energy in moments of silence.




Platform-specific items.


The suite of traits allowing CPAL to abstract over hosts, devices, event loops and stream IDs.



Some error has occurred that is specific to the backend from which it was produced.


A buffer of dynamically typed audio data, passed to raw stream callbacks.


The Device implementation associated with the platform's dynamically dispatched Host type.


The Devices iterator associated with the platform's dynamically dispatched Host type.


The platform's dynamically dispatched Host type.


The requested host, although supported on this platform, is unavailable.


Information relevant to a single call to the user's input stream data callback.


A timestamp associated with a call to an input stream's data callback.


Information relevant to a single call to the user's output stream data callback.


A timestamp associated with a call to an output stream's data callback.


The number of samples processed per second for a single channel of audio.


The Stream implementation associated with the platform's dynamically dispatched Host type.


The set of parameters used to describe how to open a stream.


A monotonic time instance associated with a stream, retrieved from either:


The SupportedInputConfigs iterator associated with the platform's dynamically dispatched Host type.


The SupportedOutputConfigs iterator associated with the platform's dynamically dispatched Host type.


Describes a single supported stream configuration, retrieved via either a SupportedStreamConfigRange instance or one of the Device::default_input/output_config methods.


Describes a range of supported stream configurations, retrieved via the Device::supported_input/output_configs method.



Error that can happen when creating a Stream.


May occur when attempting to request the default input or output stream format from a Device.


An error that may occur while attempting to retrieve a device name.


An error that might occur while attempting to enumerate the available devices on a system.


Unique identifier for available hosts on the platform.


Errors that might occur when calling pause_stream.


Errors that might occur when calling play_stream.


Format that each sample has.


Errors that might occur while a stream is running.


Error that can happen when enumerating the list of supported formats.



All hosts supported by CPAL on this platform.



Trait for containers that contain PCM data.



Produces a list of hosts that are currently available on the system.


The default host for the current compilation target platform.


Given a unique host identifier, initialise and produce the host if it is available.

Type Definitions


Number of channels.


A host's device iterator yielding only input devices.


A host's device iterator yielding only output devices.