Expand description
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 default_host 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()
methods on host
.
Alternatively, you can enumerate all the available devices with the devices()
method.
Beware that the default_*_device()
functions return an Option<Device>
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?!")
.with_max_sample_rate();
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(
&config,
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
// react to stream events and read or write stream data here.
},
move |err| {
// react to errors here.
},
None // None=blocking, Some(Duration)=timeout
);
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, FromSample};
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, None),
SampleFormat::I16 => device.build_output_stream(&config, write_silence::<i16>, err_fn, None),
SampleFormat::U16 => device.build_output_stream(&config, write_silence::<u16>, err_fn, None),
sample_format => panic!("Unsupported sample format '{sample_format}'")
}.unwrap();
fn write_silence<T: Sample>(data: &mut [T], _: &cpal::OutputCallbackInfo) {
for sample in data.iter_mut() {
*sample = Sample::EQUILIBRIUM;
}
}
Not all platforms automatically run the stream upon creation. To ensure the stream has started,
we can use Stream::play
.
stream.play().unwrap();
Some devices support pausing the audio stream. This can be useful for saving energy in moments of silence.
stream.pause().unwrap();
Modules
Structs
Host
type.SupportedInputConfigs
iterator associated with the platform’s dynamically
dispatched Host
type.SupportedOutputConfigs
iterator associated with the platform’s dynamically
dispatched Host
type.SupportedStreamConfigRange
instance or one of the
Device::default_input/output_config
methods.Device::supported_input/output_configs
method.Enums
Stream
.Device
.Stream::pause()
.Stream::play()
.Constants
Traits
From
trait, but specifically for converting between sample types.