[][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.
  • An EventLoop is a collection of streams being run by one or more Devices under a single Host. Each stream must belong to an EventLoop, and all the streams that belong to an EventLoop are managed together.

The first step is to initialise the Host (for accessing audio devices) and create an EventLoop:

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

Then choose a 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 format of the audio samples is going to be. You can query all the supported formats with the supported_input_formats() and supported_output_formats() methods. These produce a list of SupportedFormat structs which can later be turned into actual Format structs. If you don't want to query the list of formats, you can also build your own Format manually, but doing so could lead to an error when building the stream if the format is not supported by the device.

Note: the supported_formats() method could return an error for example if the device has been disconnected.

use cpal::traits::{DeviceTrait, HostTrait};
let mut supported_formats_range = device.supported_output_formats()
    .expect("error while querying formats");
let format = supported_formats_range.next()
    .expect("no supported format?!")

Now that we have everything for the stream, we can create it from our event loop:

use cpal::traits::{DeviceTrait, EventLoopTrait, HostTrait};
let stream_id = event_loop.build_output_stream(&device, &format).unwrap();

The value returned by build_output_stream() is of type StreamId and is an identifier that will allow you to control the stream.

Now we must start the stream. This is done with the play_stream() method on the event loop.

event_loop.play_stream(stream_id).expect("failed to play_stream");

Now everything is ready! We call run() on the event_loop to begin processing.

event_loop.run(move |_stream_id, _stream_result| {
    // react to stream events and read or write stream data here

Note: Calling run() will block the thread forever, so it's usually best done in a separate thread.

While run() is running, the audio device of the user will from time to time call the callback that you passed to this function. The callback gets passed the stream ID and an instance of type StreamData that represents the data that must be read from or written to. The inner UnknownTypeOutputBuffer can be one of I16, U16 or F32 depending on the format that was passed to build_output_stream.

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

use cpal::{StreamData, UnknownTypeOutputBuffer};
use cpal::traits::{EventLoopTrait, HostTrait};
event_loop.run(move |stream_id, stream_result| {
    let stream_data = match stream_result {
        Ok(data) => data,
        Err(err) => {
            eprintln!("an error occurred on stream {:?}: {}", stream_id, err);
        _ => return,

    match stream_data {
        StreamData::Output { buffer: UnknownTypeOutputBuffer::U16(mut buffer) } => {
            for elem in buffer.iter_mut() {
                *elem = u16::max_value() / 2;
        StreamData::Output { buffer: UnknownTypeOutputBuffer::I16(mut buffer) } => {
            for elem in buffer.iter_mut() {
                *elem = 0;
        StreamData::Output { buffer: UnknownTypeOutputBuffer::F32(mut buffer) } => {
            for elem in buffer.iter_mut() {
                *elem = 0.0;
        _ => (),



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.


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 EventLoop implementation associated with the platform's dynamically dispatched Host type.


The format of an input or output audio stream.


The platform's dynamically dispatched Host type.


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


Represents a buffer containing audio data that may be read.


Represents a buffer that must be filled with audio data. The buffer in unfilled state may contain garbage values.


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


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


Describes a range of supported stream formats.


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


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



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.


Stream data passed to the EventLoop::run callback.


Errors that might occur while a stream is running.


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


This is the struct that is provided to you by cpal when you want to read samples from a buffer.


This is the struct that is provided to you by cpal when you want to write samples to a buffer.



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.


Stream data passed to the EventLoop::run callback, or an error in the case that the device was invalidated or some backend-specific error occurred.