Crate cpal [−] [src]
How to use cpal
In order to play a sound, first you need to create an EventLoop
and a voice.
// getting the default sound output of the system (can return `None` if nothing is supported) let endpoint = cpal::default_endpoint().unwrap(); // note that the user can at any moment disconnect the device, therefore all operations return // a `Result` to handle this situation // getting a format for the PCM let supported_formats_range = endpoint.supported_formats().unwrap().next().unwrap(); let format = supported_formats_range.with_max_samples_rate(); let event_loop = cpal::EventLoop::new(); let voice_id = event_loop.build_voice(&endpoint, &format).unwrap(); event_loop.play(voice_id);
voice_id
is an identifier for the voice can be used to control the play/pause of the output.
Once that's done, you can call run()
on the event_loop
.
event_loop.run(move |_voice_id, _buffer| { // write data to `buffer` here });
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 call the callbacks you registered
from time to time.
Structs
Buffer |
Represents a buffer that must be filled with audio data. |
Endpoint |
An opaque type that identifies an end point. |
EndpointsIterator |
An iterator for the list of formats that are supported by the backend. |
EventLoop | |
Format |
Describes a format. |
SamplesRate | |
SupportedFormat |
Describes a format. |
SupportedFormatsIterator |
An iterator that produces a list of formats supported by the endpoint. |
VoiceId |
Identifier of a voice in an events loop. |
Enums
ChannelPosition |
Possible position of a channel. |
CreationError |
Error that can happen when creating a |
FormatsEnumerationError |
Error that can happen when enumerating the list of supported formats. |
SampleFormat |
Format that each sample has. |
UnknownTypeBuffer |
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_endpoint |
Return the default endpoint, or |
endpoints |
Return an iterator to the list of formats that are supported by the system. |
get_default_endpoint |
[ Deprecated ] Deprecated. Use |
get_endpoints_list |
[ Deprecated ] Deprecated. Use |
Type Definitions
ChannelsCount |
Number of channels. |