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::get_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 format = endpoint.get_supported_formats_list().unwrap().next().unwrap();

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

let (voice, mut samples_stream) = cpal::Voice::new(&endpoint, &format, &event_loop).unwrap();Run

The voice can be used to control the play/pause of the output, while the samples_stream can be used to register a callback that will be called whenever the backend is ready to get data. See the documentation of futures-rs for more info about how to use streams.

use futures::stream::Stream;
use futures::task;

task::spawn(samples_stream.for_each(move |buffer| -> Result<_, ()> {
    // write data to `buffer` here

    Ok(())
})).execute(my_executor);Run

TODO: add example

After you have registered a callback, call play:

voice.play();Run

And finally, run the event loop:

event_loop.run();Run

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
SamplesStream
SupportedFormatsIterator

An iterator that produces a list of formats supported by the endpoint.

Voice

Controls a sound output. A typical application has one Voice for each sound it wants to output.

Enums

ChannelPosition

Possible position of a channel.

CreationError

Error that can happen when creating a Voice.

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

get_default_endpoint

Return the default endpoint, or None if no device is available.

get_endpoints_list

Return an iterator to the list of formats that are supported by the system.

Type Definitions

ChannelsCount

Number of channels.