[][src]Crate cpal

How to use cpal

Here are some concepts cpal exposes:

  • A Device is an audio device that may have any number of input and output streams.
  • A stream is an open audio channel. Input streams allow you to receive audio data, output streams allow you to play audio data. You must choose which Device runs your stream before you create one.
  • An EventLoop is a collection of streams being run by one or more Device. Each stream must belong to an EventLoop, and all the streams that belong to an EventLoop are managed together.

The first step is to create an EventLoop:

use cpal::EventLoop;
let event_loop = EventLoop::new();

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 = cpal::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.

let mut supported_formats_range = device.supported_output_formats()
    .expect("error while querying formats");
let format = supported_formats_range.next()
    .expect("no supported format?!")
    .with_max_sample_rate();

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

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

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

event_loop.run(move |_stream_id, _stream_data| {
    // 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};

event_loop.run(move |_stream_id, mut stream_data| {
    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;
            }
        },
        _ => (),
    }
});

Structs

Device

An opaque type that identifies a device that is capable of either audio input or output.

Devices

An iterator yielding all Devices currently available to the system.

EventLoop

Collection of voices managed together.

Format

The format of an input or output audio stream.

InputBuffer

Represents a buffer containing audio data that may be read.

OutputBuffer

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

SampleRate

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

StreamId

Identifier of a stream within the EventLoop.

SupportedFormat

Describes a range of supported stream formats.

SupportedInputFormats

An iterator that produces a list of input stream formats supported by the device.

SupportedOutputFormats

An iterator that produces a list of output stream formats supported by the device.

Enums

CreationError

Error that can happen when creating a Voice.

DefaultFormatError

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

FormatsEnumerationError

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

SampleFormat

Format that each sample has.

StreamData

Stream data passed to the EventLoop::run callback.

UnknownTypeInputBuffer

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

UnknownTypeOutputBuffer

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

Traits

Sample

Trait for containers that contain PCM data.

Functions

default_input_device

The default input audio device on the system.

default_output_device

The default output audio device on the system.

devices

An iterator yielding all Devices currently available to the system.

input_devices

An iterator yielding all Devices currently available to the system that support one or more input stream formats.

output_devices

An iterator yielding all Devices currently available to the system that support one or more output stream formats.

Type Definitions

ChannelCount

Number of channels.

InputDevices

A Devices yielding only input devices.

OutputDevices

A Devices yielding only output devices.