### Simple Sequential Playback Example Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md A complete example demonstrating how to set up a sink, create a queue, add multiple MP3 files to it, and play them sequentially. Includes necessary imports and error handling. ```rust use rodio::queue::queue; use rodio::{DeviceSinkBuilder, Decoder}; use std::fs::File; fn main() -> Result<(), Box> { let sink = DeviceSinkBuilder::open_default_sink()?; let (queue_input, queue_output) = queue(false); sink.mixer().add(queue_output); // Add files in order queue_input.append(Decoder::try_from(File::open("song1.mp3")?)?); queue_input.append(Decoder::try_from(File::open("song2.mp3")?)?); queue_input.append(Decoder::try_from(File::open("song3.mp3")?)?); std::thread::sleep(std::time::Duration::from_secs(300)); Ok(()) } ``` -------------------------------- ### Usage Examples Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md Provides practical examples of how to use Rodio's queue functionality for simple sequential playback. ```APIDOC ### Simple Sequential Playback ```rust use rodio::queue::queue; use rodio::{DeviceSinkBuilder, Decoder}; use std::fs::File; fn main() -> Result<(), Box> { let sink = DeviceSinkBuilder::open_default_sink()?; let (queue_input, queue_output) = queue(false); sink.mixer().add(queue_output); // Add files in order queue_input.append(Decoder::try_from(File::open("song1.mp3")?)?); queue_input.append(Decoder::try_from(File::open("song2.mp3")?)?); queue_input.append(Decoder::try_from(File::open("song3.mp3")?)?); std::thread::sleep(std::time::Duration::from_secs(300)); Ok(()) } ``` ``` -------------------------------- ### Simple File Playback with Rodio Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/decoder.md Play an audio file using `Decoder::try_from` and add it to the default output sink. This example demonstrates basic playback setup and requires a 10-second sleep to allow playback. ```rust use std::fs::File; use rodio::{Decoder, DeviceSinkBuilder}; fn main() -> Result<(), Box> { let sink_handle = DeviceSinkBuilder::open_default_sink()?; let mixer = sink_handle.mixer(); let file = File::open("music.mp3")?; let source = Decoder::try_from(file)?; mixer.add(source); std::thread::sleep(std::time::Duration::from_secs(10)); Ok(()) } ``` -------------------------------- ### Initialize Mixer with Stereo and 48kHz Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Example of initializing a mixer with stereo channels and a 48kHz sample rate, then adding sources. ```rust use rodio::mixer::mixer; use std::num::NonZero; let (mixer, source) = mixer( NonZero::new(2).unwrap(), // Stereo NonZero::new(48_000).unwrap() // 48 kHz ); // Add sources to mixer mixer.add(source1); mixer.add(source2); ``` -------------------------------- ### Configure Device Sink Builder Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Example of creating a DeviceSinkBuilder from the default device and then customizing its channel count and sample rate. ```rust let builder = DeviceSinkBuilder::from_default_device()? .with_channels(nz!(2)) .with_sample_rate(nz!(48_000)); ``` -------------------------------- ### MicrophoneBuilder::new Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Creates a new microphone builder for configuring input settings. This is the starting point for setting up a microphone. ```APIDOC ## MicrophoneBuilder::new ### Description Creates a new microphone builder for configuring input settings. ### Method `pub fn new() -> MicrophoneBuilder` ### Returns - `MicrophoneBuilder`: An instance of the builder. ### Example ```rust let builder = MicrophoneBuilder::new(); ``` ``` -------------------------------- ### Use Default Sink to Play Audio Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Example of opening the default audio sink and adding an audio source to it for playback. ```rust let sink = rodio::DeviceSinkBuilder::open_default_sink()?; let mixer = sink.mixer(); mixer.add(source); ``` -------------------------------- ### Player::new Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/player.md Creates a new unconnected player. This is the default way to instantiate a Player, providing a starting point for audio playback. ```APIDOC ## Player::new() ### Description Creates a new unconnected player. This is the default way to instantiate a Player, providing a starting point for audio playback. ### Associated Function `Player::new` ### Example ```rust let (player, source) = Player::new(); ``` ``` -------------------------------- ### Example of Cloning a Buffered Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-generators-and-filters.md Demonstrates how to clone a buffered audio source, which is not possible with non-buffered sources. This allows for multiple instances or references to the same buffered audio data. ```rust let sine = SineWave::new(440.0).buffered(); let clone = sine.clone(); // Can clone buffered sources ``` -------------------------------- ### Sink Drop Behavior Example Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Demonstrates the lifecycle of a sink, showing how audio playback stops automatically when the sink goes out of scope and is dropped. ```rust { let sink = DeviceSinkBuilder::open_default_sink()?; mixer.add(source); // Audio plays here } // Sink dropped, playback stops ``` -------------------------------- ### Configure Microphone with Preferred Settings Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md This example shows how to configure a microphone with specific preferences for channel counts, sample rates, and buffer sizes. The builder attempts to match these preferences in the order provided. ```rust use rodio::microphone::MicrophoneBuilder; use std::num::NonZero; fn main() -> Result<(), Box> { let mut builder = MicrophoneBuilder::new() .default_device()? .default_config()? .prefer_channel_counts([ NonZero::new(2).unwrap(), // Stereo NonZero::new(1).unwrap(), // Mono fallback ]) .prefer_sample_rates([ NonZero::new(48_000).unwrap(), // 48 kHz NonZero::new(44_100).unwrap(), // 44.1 kHz NonZero::new(16_000).unwrap(), // 16 kHz ]) .prefer_buffer_sizes(512..4096); let mic = builder.open_stream()?; Ok(()) } ``` -------------------------------- ### Microphone Source Trait Example Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Demonstrates using Microphone as a Source, including recording for a specific duration and amplifying the audio. ```rust use rodio::Source; use std::time::Duration; let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .open_stream()?; // Record for 3 seconds let recording = mic.take_duration(Duration::from_secs(3)); // Apply amplification let loud_recording = recording.amplify(2.0); ``` -------------------------------- ### Recording and Playback Simultaneously Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md This example demonstrates how to record audio from a microphone and play it back through the default audio output device concurrently. It uses `DeviceSinkBuilder` for output and `MicrophoneBuilder` for input. ```rust use rodio::microphone::MicrophoneBuilder; use rodio::{DeviceSinkBuilder, Source}; use std::time::Duration; fn main() -> Result<(), Box> { // Set up output let sink = DeviceSinkBuilder::open_default_sink()?; let mixer = sink.mixer(); // Set up input let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .open_stream()?; // Record and play back simultaneously let recording = mic.take_duration(Duration::from_secs(5)); mixer.add(recording); std::thread::sleep(Duration::from_secs(5)); Ok(()) } ``` -------------------------------- ### Basic Microphone Recording Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md A fundamental example of setting up a microphone, opening a stream, and recording audio for a set duration. The recorded audio can then be processed further. ```rust use rodio::microphone::MicrophoneBuilder; use rodio::Source; use std::time::Duration; fn main() -> Result<(), Box> { let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .open_stream()?; // Record for 3 seconds let recording = mic.take_duration(Duration::from_secs(3)); // Now you can use recording like any other Source // e.g., play it back, save it, process it Ok(()) } ``` -------------------------------- ### Select Audio Output Device Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Selects a specific audio output device. The example shows how to enumerate available devices and create a builder from the first one found. ```rust let host = cpal::default_host(); let mut devices = host.output_devices()?; // Get first device if let Some(device) = devices.next() { let builder = DeviceSinkBuilder::from_device(device)?; } ``` -------------------------------- ### Configure Custom Recording Microphone Setup Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Sets up a microphone stream with specific preferences for channels, sample rates, and buffer sizes. This allows fine-tuning of audio input. ```rust let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .prefer_channels([nz!(1), nz!(2)]) .prefer_sample_rates([nz!(16_000), nz!(44_100)]) .prefer_buffer_sizes(256..1024) .open_stream()?; ``` -------------------------------- ### Dynamic Queue Management with Multiple Sources Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md Demonstrates how to dynamically add multiple audio sources to a queue over time from different threads. Includes an example of clearing all queued sources. ```rust let (input, output) = queue(true); mixer.add(output); // Initially add one source input.append(source1); // Later, add more sources from another thread std::thread::spawn(move || { std::thread::sleep(Duration::from_secs(5)); input.append(source2); input.append(source3); }); // Clear queued sources at any time std::thread::spawn(move || { std::thread::sleep(Duration::from_secs(30)); input.clear(); // Skip to next append_with_signal }); ``` -------------------------------- ### Configuring Default Sink with Builders Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/README.md Use the builder pattern for ergonomic configuration of audio output devices. This example opens the default sink with custom channel and sample rate settings. ```rust DeviceSinkBuilder::open_default_sink()? .with_channels(nz!(2)) .with_sample_rate(nz!(48_000)) .open_stream()? ``` -------------------------------- ### Example Usage of nz! Macro Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/types.md Demonstrates the usage of the nz! macro to create NonZero values for channel counts and sample rates. This provides a shorter alternative to NonZero::new(value).unwrap(). ```rust let channels = nz!(2); // Instead of NonZero::new(2).unwrap() let sample_rate = nz!(48_000); ``` -------------------------------- ### Example Usage of Limiter Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-generators-and-filters.md Applies a limiter to an audio source with specified threshold, knee width, attack, and release times. Useful for loudness normalization. ```rust source.limit(LimitSettings { threshold: -6.0, knee_width: 12.0, attack: Duration::from_millis(5), release: Duration::from_millis(100), }) ``` -------------------------------- ### Enable MP3 Decoding Feature Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Example of how to enable the `mp3` feature in Cargo.toml to support MP3 audio format decoding. ```toml # Cargo.toml - to support MP3 [dependencies] rodio = { version = "0.22", features = ["mp3"] } ``` -------------------------------- ### Create a Chirp (Frequency Sweep) Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-generators-and-filters.md Generates a source that sweeps in frequency from a start to an end frequency over a specified duration. Requires importing `chirp` and `Duration`. ```rust use rodio::source::chirp; use std::time::Duration; let sweep = chirp(100.0, 1000.0, Duration::from_secs(2)); mixer.add(sweep); ``` -------------------------------- ### open_stream Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Opens the audio input stream with the currently configured settings. This is the final step to get an active microphone input. ```APIDOC ## open_stream() -> Result ### Description Opens the audio input stream with the currently configured settings. This is the final step to get an active microphone input. ### Method ``` pub fn open_stream(self) -> Result ``` ### Returns - **Microphone** - On success, returns a Microphone instance. - **MicrophoneError** - On failure, returns an error. ### Request Example ```rust let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .open_stream()?; ``` ``` -------------------------------- ### Example Commit Message Source: https://github.com/rustaudio/rodio/blob/master/CONTRIBUTING.md Follow this structure for clear and informative commit messages, including a concise subject line, a detailed body if necessary, and references to issues. ```git Add spatial audio support for stereo sources - Implement SpatialSource struct - Add panning and distance attenuation - Update documentation for spatial audio usage Fixes #456 ``` -------------------------------- ### Configuring Microphone Input with Builders Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/README.md Use the MicrophoneBuilder to configure microphone input, including selecting a default device, setting preferred channel counts, and sample rates. This example opens a stream with specific preferences. ```rust let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .prefer_channels([nz!(2), nz!(1)]) .prefer_sample_rates([nz!(48_000), nz!(44_100)]) .open_stream()? ``` -------------------------------- ### Example Usage of Dithering Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-generators-and-filters.md Applies dithering to an audio source, targeting a specific bit depth and using a chosen algorithm. Recommended for high-quality audio reduction. ```rust source .amplify(0.5) .dither(BitDepth::new(16).unwrap(), DitherAlgorithm::Triangular) ``` -------------------------------- ### Handle Microphone Initialization Errors Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md This snippet illustrates how to handle potential errors when trying to get a default microphone device. It uses a `match` statement to differentiate between success and failure, printing an error message if no microphone is available. ```rust match MicrophoneBuilder::new().default_device() { Ok(builder) => { /* ... */ }, Err(e) => eprintln!("No microphone available: {}", e), } ``` -------------------------------- ### Accessing Input Device Information Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Shows how to get a list of available input devices and print their display names. The `Input` struct implements `Display` for easy printing. ```rust let inputs = available_inputs()?; let first = &inputs[0]; println!("Using device: {}", first); // Display trait ``` -------------------------------- ### Get audio sink configuration details Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Retrieves and prints the configuration details of an active audio sink, including channel count, sample rate, and buffer size. ```rust let config = sink.config(); println!("Channels: {}", config.channel_count()); println!("Sample rate: {} Hz", config.sample_rate()); ``` -------------------------------- ### Open an audio stream with custom sample rate Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Opens an audio stream using the default device and a configured sample rate of 48 kHz. This is a common setup for many audio applications. ```rust let sink = DeviceSinkBuilder::from_default_device()? .with_sample_rate(nz!(48_000)) .open_stream()?; ``` -------------------------------- ### Chirp Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-generators-and-filters.md Generates a frequency sweep (chirp) from a start frequency to an end frequency over a specified duration. ```APIDOC ## Chirp ### Description Generates a frequency sweep (chirp) from start to end frequency over a specified duration. ### Constructor ```rust pub fn chirp(start_freq: Float, end_freq: Float, duration: Duration) -> Chirp ``` ### Parameters #### Query Parameters - **start_freq** (Float) - Required - Starting frequency in Hz - **end_freq** (Float) - Required - Ending frequency in Hz - **duration** (Duration) - Required - Duration of the sweep ### Example ```rust use rodio::source::chirp; use std::time::Duration; let sweep = chirp(100.0, 1000.0, Duration::from_secs(2)); mixer.add(sweep); ``` ``` -------------------------------- ### Get Current Playback Speed Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/player.md Returns the current playback speed multiplier. 1.0 indicates normal speed. ```rust pub fn speed(&self) -> f32 ``` ```rust let current_speed = player.speed(); println!("Playing at {}x speed", current_speed); ``` -------------------------------- ### Configure Decoder with Data and Hint Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Build a decoder instance by providing audio data and an optional format hint. The hint helps when file extensions are ambiguous or missing. ```rust pub fn with_data(self, data: R) -> DecoderBuilder pub fn with_hint(self, hint: &str) -> DecoderBuilder pub fn build(self) -> Result, DecoderError> ``` ```rust let decoder = Decoder::builder() .with_data(file) .with_hint("mp3") .build()?; ``` -------------------------------- ### Basic Audio Playback with Rodio Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Sets up a default audio sink, loads an MP3 file, decodes it, adds it to the mixer, and plays it for a specified duration. ```rust use rodio::{DeviceSinkBuilder, Decoder}; use std::fs::File; fn main() -> Result<(), Box> { let sink = DeviceSinkBuilder::open_default_sink()?; let mixer = sink.mixer(); let file = File::open("music.mp3")?; let source = Decoder::try_from(file)?; mixer.add(source); std::thread::sleep(std::time::Duration::from_secs(5)); Ok(()) } ``` -------------------------------- ### Get Current Volume Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/player.md Retrieves the current volume level of the player. The value is a multiplier where 1.0 represents normal volume. ```rust pub fn volume(&self) -> Float ``` ```rust let current_vol = player.volume(); println!("Current volume: {}", current_vol); ``` -------------------------------- ### MicrophoneBuilder::default_device Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Configures the builder to use the system's default input device. This is a convenient method for quick setup. ```APIDOC ## MicrophoneBuilder::default_device ### Description Uses the system's default input device. ### Method `pub fn default_device(self) -> Result` ### Returns - `Result`: The builder instance on success, or an error if the default device cannot be set. ### Example ```rust let builder = MicrophoneBuilder::new() .default_device()?; ``` ``` -------------------------------- ### Create New Player and Source Queue Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/player.md Use this to create a new Player and its associated audio source queue. The output source needs to be added to a mixer. ```rust pub fn new() -> (Player, queue::SourcesQueueOutput) ``` ```rust let (player, source) = rodio::Player::new(); mixer.add(source); ``` -------------------------------- ### MicrophoneBuilder::default_config Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Configures the builder to use the device's default input configuration. This simplifies setup by applying standard settings. ```APIDOC ## MicrophoneBuilder::default_config ### Description Uses the device's default input configuration. ### Method `pub fn default_config(self) -> Result` ### Returns - `Result`: The builder instance on success, or an error if the default configuration cannot be applied. ### Example ```rust let builder = MicrophoneBuilder::new() .default_device()?; .default_config()?; ``` ``` -------------------------------- ### List Available Microphones and Select One Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md This snippet demonstrates how to list all available input devices and select a specific one by its index. Ensure that the desired device index is valid before attempting to open the stream. ```rust use rodio::microphone::{MicrophoneBuilder, available_inputs}; fn main() -> Result<(), Box> { let inputs = available_inputs()?; println!("Available input devices:"); for (i, device) in inputs.iter().enumerate() { println!(" {}: {}", i, device); } // Use the second device if inputs.len() > 1 { let mic = MicrophoneBuilder::new() .device(inputs[1].clone())? .default_config()? .open_stream()?; println!("Using: {}", inputs[1]); } Ok(()) } ``` -------------------------------- ### Fade In Audio Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-generators-and-filters.md Gradually increases the volume of an audio source from 0 to normal over a specified duration. Use this for smooth audio starts. ```rust pub fn fade_in(self, duration: Duration) -> FadeIn where Self: Sized ``` ```rust source.fade_in(Duration::from_secs(2)) // 2-second fade in ``` -------------------------------- ### Prefer Default or Alternative Buffer Sizes Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Shows how to configure buffer sizes, either by using the device's default or trying a range of compatible values. ```rust builder.prefer_buffer_sizes(512..4096) ``` -------------------------------- ### Apply Fade-In Effect to Audio Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-trait.md Use `fade_in` to gradually increase the volume of an audio source over a specified duration. This creates a smooth start. ```rust fn fade_in(self, duration: Duration) -> FadeIn where Self: Sized ``` ```rust let source = Decoder::try_from(file)? .fade_in(Duration::from_secs(2)); // 2-second fade in ``` -------------------------------- ### Skip Initial Audio Segment Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-trait.md Use `skip_duration` to ignore the first N seconds of an audio source. This is helpful for starting playback after an intro. ```rust fn skip_duration(self, duration: Duration) -> SkipDuration where Self: Sized ``` ```rust let source = Decoder::try_from(file)? .skip_duration(Duration::from_secs(10)); // Skip first 10 seconds ``` -------------------------------- ### FromIter Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/types.md Creates an audio source from any iterator that yields audio samples. ```APIDOC ## FromIter ### Description Source from an iterator. ### Constructor `from_iter(iter: I)` ``` -------------------------------- ### Rodio Minimal Build Configuration Source: https://github.com/rustaudio/rodio/blob/master/README.md Configure Rodio to exclude default features and include specific format decoders for minimal builds, useful in environments without audio output. ```toml [dependencies] rodio = { version = "0.22.1", default-features = false, features = ["symphonia-all"] } ``` -------------------------------- ### Error Propagation with Try Operator Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Example of using the try operator (`?`) for concise error propagation when opening a default sink, file, and decoding audio. ```rust fn play_audio() -> Result<(), Box> { let sink = DeviceSinkBuilder::open_default_sink()?; let file = File::open("music.mp3")?; let source = Decoder::try_from(file)?; sink.mixer().add(source); Ok(()) } ``` -------------------------------- ### Open Microphone Stream Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Opens the audio input stream with the currently configured settings in the MicrophoneBuilder. This is the final step to get a usable Microphone object. ```rust let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .open_stream()?; ``` -------------------------------- ### Handling Seeking on Unsupported Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Illustrates an error when attempting to seek on an audio source that does not support seeking. Use sources that support seeking or buffer the source first. ```rust let mut sine = SineWave::new(440.0); sine.try_seek(Duration::from_secs(1))?; // ERROR: SeekError::NotSupported ``` -------------------------------- ### Example Usage of Automatic Gain Control Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-generators-and-filters.md Applies Automatic Gain Control to an audio source with specified settings. Recommended for microphone input and variable-volume sources. ```rust source.automatic_gain_control(AutomaticGainControlSettings { target_level: 1.0, attack_time: Duration::from_secs(4), release_time: Duration::from_secs(0), absolute_max_gain: 5.0, }) ``` -------------------------------- ### Player Configuration Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Configure runtime player parameters like volume, speed, and playback state. ```APIDOC # Player Configuration The `Player` type has runtime-configurable parameters. **Module**: `rodio::player` ## Parameters Table | Parameter | | Type | | Range | | Default | | Description | | `volume` | | `Float` | | 0.0 - ∞ | | 1.0 | | Volume multiplier | | `speed` | | `f32` | | 0.0 - ∞ | | 1.0 | | Playback speed (affects pitch) | | `paused` | | `bool` | | true/false | | false | | Paused state | --- ## Configuration Methods ```rust pub fn set_volume(&self, value: Float) pub fn set_speed(&self, value: f32) pub fn pause(&self) pub fn play(&self) pub fn try_seek(&self, pos: Duration) -> Result<(), SeekError> ``` **Volume Examples**: ```rust player.set_volume(0.0); // Mute player.set_volume(0.5); // Half volume player.set_volume(1.0); // Normal volume player.set_volume(2.0); // Double volume ``` **Speed Examples**: ```rust player.set_speed(0.5); // Half speed, lower pitch player.set_speed(1.0); // Normal speed player.set_speed(1.5); // 1.5x speed, higher pitch player.set_speed(2.0); // Double speed, double pitch ``` ``` -------------------------------- ### Create SamplesBuffer with ChannelCount and SampleRate Source: https://github.com/rustaudio/rodio/blob/master/UPGRADE.md Use the `nz!` macro for easy creation of `ChannelCount` and `SampleRate` from literals, or construct them at runtime using `NonZero`. ```rust SamplesBuffer::new(nz!(1), nz!(44100)) ``` ```rust SamplesBuffer::new(NonZero::new(channel_count)?, NonZero::new(sample_rate)?) ``` -------------------------------- ### Create SamplesBuffer Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md Instantiates a new in-memory audio buffer with specified channels, sample rate, and audio data. The data can be provided as a Vec or any type that can be converted into a Vec of Samples. ```rust use rodio::buffer::SamplesBuffer; use std::num::NonZero; let samples = vec![0.0, 0.5, 0.0, -0.5, 0.0, 0.5]; let buffer = SamplesBuffer::new( NonZero::new(1).unwrap(), // Mono NonZero::new(44100).unwrap(), // 44.1 kHz samples ); mixer.add(buffer); ``` -------------------------------- ### sample_rate() Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-trait.md Gets the sample rate of the audio source, indicating samples per second per channel. This is vital for accurate audio playback speed and pitch. ```APIDOC ## sample_rate() ### Description Returns the sample rate of the audio source, measured in samples per second per channel. This determines the playback speed and pitch of the audio. ### Method `sample_rate(&self) -> SampleRate` ### Parameters None ### Returns - `SampleRate`: A `NonZero` representing the sample rate (e.g., 44100, 48000). ### Example ```rust impl Source for MySource { fn sample_rate(&self) -> SampleRate { nz!(48_000) // 48 kHz } // ... other methods } ``` ``` -------------------------------- ### Player::new Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/player.md Creates a new Player and its associated internal source queue output. The player handle and the source output are returned as a tuple. ```APIDOC ## Player::new ### Description Creates a new Player and returns both the player handle and its internal source output. ### Returns - `(Player, queue::SourcesQueueOutput)` - A tuple containing the player control handle and the internal source that implements `Source` trait. ### Example ```rust let (player, source) = rodio::Player::new(); mixer.add(source); ``` ``` -------------------------------- ### Error Recovery Pattern with Fallback Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Demonstrates a pattern to first try opening the default audio device and fall back to manual device selection if the default fails. This is useful for ensuring playback continuity. ```rust fn open_with_fallback() -> Result { // Try default first match DeviceSinkBuilder::open_default_sink() { Ok(sink) => Ok(sink), Err(_) => { // Fall back to manual device selection let devices = cpal::default_host().output_devices() .map_err(|_| DeviceSinkError::NoDevice)?; for device in devices { if let Ok(sink) = DeviceSinkBuilder::from_device(device) .and_then(|b| b.open_stream()) { return Ok(sink); } } Err(DeviceSinkError::NoDevice) } } } ``` -------------------------------- ### Create Player and Connect to Mixer Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/player.md Creates a new Player and automatically connects it to a provided mixer for immediate playback management. ```rust pub fn connect_new(mixer: &Mixer) -> Player ``` ```rust let handle = rodio::DeviceSinkBuilder::open_default_sink()?; let player = rodio::Player::connect_new(&handle.mixer()); ``` -------------------------------- ### Generate Frequency Sweep (Chirp) Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/types.md Generates an audio source with a frequency sweep from a start to an end frequency over a duration. Ideal for sound effects or testing frequency response. ```rust let sweep = chirp(100.0, 1000.0, Duration::from_secs(2)); ``` -------------------------------- ### Ensure Complete Frames in Custom Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Illustrates how to prevent frame alignment issues by ensuring custom audio sources emit complete frames, padding with silence if necessary. ```rust impl Source for MySource { fn next(&mut self) -> Option { // Track position and pad incomplete frames if self.is_last_sample() && self.position % self.channels() != 0 { // Emit silence to complete the frame return Some(0.0); } // ... } } ``` -------------------------------- ### Implementing channels for a Custom Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-trait.md Implement `channels` to return the number of audio channels. Use `nz!(2)` for stereo. ```rust impl Source for MySource { fn channels(&self) -> ChannelCount { nz!(2) // Stereo: 2 channels } } ``` -------------------------------- ### Update Decoder Initialization (Rodio 0.21) Source: https://github.com/rustaudio/rodio/blob/master/UPGRADE.md Rodio 0.21 simplifies decoder initialization for files. The `Decoder::new` method no longer accepts a `BufReader` or an `Mp4Type` hint. Use `Decoder::try_from` directly on a `File`. ```rust let file = File::open("music.ogg")?; let source = Decoder::try_from(file)?; ``` -------------------------------- ### Run Benchmarks with Cargo Source: https://github.com/rustaudio/rodio/blob/master/CONTRIBUTING.md Execute performance benchmarks using `cargo bench` to assess the efficiency of your changes. ```bash cargo bench ``` -------------------------------- ### Rodio Cargo Feature Flags Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/README.md Enable optional functionality in Rodio by specifying features in your Cargo.toml file. This example shows how to enable various audio formats, generators, and other features. ```toml [dependencies] rodio = { version = "0.22", features = [ "playback", # Audio output (default) "recording", # Microphone input (default) "flac", "mp3", "vorbis", "mp4", "wav", # Audio formats (default) "noise", # Noise generators "dither", # Dithering "64bit", # f64 precision "simd", # Accelerated decoding (default) "realtime-dbus", # Low-latency scheduling ] } ``` -------------------------------- ### Open Default Stream with OutputStreamBuilder Source: https://github.com/rustaudio/rodio/blob/master/UPGRADE.md Recommended approach to open a new output stream for the default output device with its default configuration. It attempts alternative configurations or non-default devices if the initial attempt fails. ```rust OutputStreamBuilder::open_default_stream()? ``` -------------------------------- ### Create Decoder from Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/decoder.md Creates a decoder from a readable source like a file or buffer. This is the recommended simple approach for decoding audio. ```rust use std::fs::File; use rodio::Decoder; let file = File::open("audio.mp3")?; let decoder = Decoder::try_from(file)?; ``` -------------------------------- ### Add Source and Get Completion Signal Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md Adds a source to the queue and returns a receiver that will be signaled when the source finishes playing. This allows for synchronization or triggering actions upon source completion. ```rust pub fn append_with_signal(&self, source: T) -> Receiver<()> where T: Source + Send + 'static ``` ```rust let done_rx = input.append_with_signal(source); // Block until source finishes done_rx.recv().ok(); // Ignore error if queue dropped println!("Source finished!"); ``` -------------------------------- ### Full Codec Support Configuration Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Configure Rodio with full codec support, including recording and WAV output capabilities. ```toml rodio = { version = "0.22", features = [ "symphonia-all", "recording", "wav_output", ] } ``` -------------------------------- ### Create a New Microphone Builder Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Initializes a new MicrophoneBuilder instance. This builder is used to configure the settings for audio input before creating a Microphone instance. ```rust let builder = MicrophoneBuilder::new(); ``` -------------------------------- ### Set PulseAudio Configuration Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Configure the PulseAudio server using an environment variable. ```bash # Set PulseAudio server export PULSE_SERVER=unix:/run/pulse/native ``` -------------------------------- ### Rodio with Default Features Disabled Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Configures Rodio in Cargo.toml to exclude default features and include specific features like symphonia-all and wav_output. This is for headless server setups where no audio device is present. ```toml # Cargo.toml rodio = { version = "0.22", default-features = false, features = [ "symphonia-all", "wav_output", ] } ``` -------------------------------- ### Player::connect_new Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/player.md Creates a new Player and immediately connects it to a provided mixer for automatic playback. Returns the player handle. ```APIDOC ## Player::connect_new ### Description Creates a new Player and immediately connects it to a mixer for automatic playback. ### Parameters #### Path Parameters - **mixer** (`&Mixer`) - Required - Reference to the mixer to add this player to ### Returns - `Player` - The player handle ### Example ```rust let handle = rodio::DeviceSinkBuilder::open_default_sink()?; let player = rodio::Player::connect_new(&handle.mixer()); ``` ``` -------------------------------- ### Configure High-Quality Playback Stream Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Set up a default audio output sink with specific channel count, sample rate, and buffer size for high-quality playback. ```rust use std::num::NonZero; let sink = DeviceSinkBuilder::open_default_sink()? .with_channels(NonZero::new(2).unwrap()) // Stereo .with_sample_rate(NonZero::new(96_000).unwrap()) // 96 kHz .with_buffer_size(BufferSize::Fixed(4096)) // Stable .open_stream()?; ``` -------------------------------- ### Recover from Unsupported Sample Rate Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Demonstrates how to recover from unsupported sample rates by falling back to a list of preferred sample rates. ```rust match builder.try_sample_rate(nz!(96_000)) { Ok(b) => { /* use it */ }, Err(_) => { // Fall back to common rates let builder = builder.prefer_sample_rates([ nz!(48_000), nz!(44_100), nz!(16_000), ]); }, } ``` -------------------------------- ### Get Duration with Byte Length Guarantee Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/decoder.md Ensure accurate duration calculation for MP3/Vorbis files by providing the byte length using `with_byte_len()` before building the decoder. This is crucial for formats where duration cannot be determined solely from the stream. ```rust use std::fs::File; use rodio::Decoder; fn main() -> Result<(), Box> { let file = File::open("audio.mp3")?; let len = file.metadata()?.len(); let decoder = Decoder::builder() .with_data(file) .with_byte_len(len) .build()?; println!("Duration: {:?}", decoder.total_duration()); Ok(()) } ``` -------------------------------- ### Basic Error Handling for Audio Playback Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/README.md Handle potential errors during audio playback setup, including opening the default sink, opening audio files, and decoding them. This function returns a Result to propagate errors. ```rust fn play_audio() -> Result<(), Box> { let sink = DeviceSinkBuilder::open_default_sink()?; let file = File::open("audio.mp3")?; let source = Decoder::try_from(file)?; sink.mixer().add(source); Ok(()) } ``` -------------------------------- ### Decoder::try_from Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/decoder.md Creates a decoder from a readable source. This is the recommended simple approach for decoding audio files. ```APIDOC ## Decoder::try_from(source: R) -> Result, DecoderError> ### Description Creates a decoder from a readable source (file, buffer, etc.). This is the recommended simple approach. ### Method `impl TryFrom for Decoder` ### Type Parameters - **R**: `Read + Seek + 'static` - Reader source (typically File or BufReader) ### Returns `Result, DecoderError>` ### Example ```rust use std::fs::File; use rodio::Decoder; let file = File::open("audio.mp3")?; let decoder = Decoder::try_from(file)?; ``` ### Note For proper duration calculation with MP3/Vorbis, ensure the File is passed directly (metadata().len() is automatically retrieved). ``` -------------------------------- ### Sequential Playback with Frame Alignment Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md Demonstrates how Rodio ensures frame alignment between sequential audio sources by injecting silence if necessary, preventing audio glitches during transitions. ```rust // Create mono source with odd sample count let odd_samples = vec![0.0, 0.5, 0.0]; // 3 samples (incomplete frame) let buffer1 = SamplesBuffer::new(nz!(1), nz!(44100), odd_samples); let buffer2 = SamplesBuffer::new(nz!(1), nz!(44100), vec![/* ... */]); let (input, output) = queue(true); input.append(buffer1); // 3 samples input.append(buffer2); // Frame-aligned start // Output: // 0.0, 0.5, 0.0, [silence], [buffer2 samples...] ``` -------------------------------- ### Configure Microphone with Default Settings Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/microphone.md Applies the default input configuration to the microphone builder. This method should be chained after selecting a device. ```rust let builder = MicrophoneBuilder::new() .default_device()? .default_config()?; ``` -------------------------------- ### Configure Default Microphone Input Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Initializes the MicrophoneBuilder to use the system's default audio input device. ```rust let builder = MicrophoneBuilder::new().default_device()?; ``` -------------------------------- ### Basic Audio Playback Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/README.md Opens the default audio output device and plays an MP3 file. Requires a file named 'music.mp3' in the current directory. ```rust use rodio::{DeviceSinkBuilder, Decoder}; use std::fs::File; let sink = DeviceSinkBuilder::open_default_sink()?; let file = File::open("music.mp3")?; let source = Decoder::try_from(file)?; sink.mixer().add(source); ``` -------------------------------- ### Recording from Microphone Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/README.md Configures and opens a stream from the default microphone, then records audio for a specified duration. Requires microphone access. ```rust use rodio::microphone::MicrophoneBuilder; use std::time::Duration; let mic = MicrophoneBuilder::new() .default_device()? .default_config()? .open_stream()?; let recording = mic.take_duration(Duration::from_secs(5)); ``` -------------------------------- ### Implementing sample_rate for a Custom Source Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/source-trait.md Implement `sample_rate` to return the sample rate in samples per second per channel. Common values include 44100, 48000, and 96000. ```rust impl Source for MySource { fn sample_rate(&self) -> SampleRate { nz!(48_000) // 48 kHz } } ``` -------------------------------- ### FromFactoryIter Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/types.md Creates an audio source from a factory function that produces samples. This is useful for generating audio procedurally. ```APIDOC ## `FromFactoryIter` Source from a sample-producing factory function. ### Constructor `from_factory(channels, sample_rate, factory_fn)` ### Module `rodio::source::from_factory` ``` -------------------------------- ### Create Device Sink Builder from Default Device Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Creates a DeviceSinkBuilder pre-configured with the default audio device's parameters, allowing for further customization. ```rust pub fn from_default_device() -> Result ``` -------------------------------- ### Create a Sequential Audio Queue Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md Creates a queue for sequential audio playback. Use `keep_alive_if_empty = true` to output silence when empty, waiting for new sources. Use `false` to end the queue when all sources are exhausted. ```rust pub fn queue(keep_alive_if_empty: bool) -> (Arc, SourcesQueueOutput) ``` ```rust use rodio::queue::queue; let (input, output) = queue(true); // Keep alive if empty mixer.add(output); // Add sources from any thread input.append(source1); input.append(source2); // source1 plays, then source2 ``` -------------------------------- ### Configure Decoder with Byte Length Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/configuration.md Build a decoder instance, providing the total byte length of the audio file. This is required for accurate duration calculation with variable-bitrate formats. ```rust pub fn with_data(self, data: R) -> DecoderBuilder pub fn with_byte_len(self, len: u64) -> DecoderBuilder pub fn build(self) -> Result, DecoderError> ``` ```rust let file = File::open("audio.mp3")?; let len = file.metadata()?.len(); let decoder = Decoder::builder() .with_data(file) .with_byte_len(len) // Required for accurate duration .build()?; ``` -------------------------------- ### DecoderBuilder::with_hint Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/decoder.md Provides a format hint (like file extension or MIME type) for ambiguous audio inputs to the decoder builder. ```APIDOC ## DecoderBuilder::with_hint(hint: &str) -> DecoderBuilder ### Description Provides a format hint for ambiguous inputs (file extension, MIME type, etc.). ### Method `pub fn with_hint(self, hint: &str) -> DecoderBuilder` ### Parameters - **hint**: `&str` - Required - Format hint like "mp3", "wav", "flac", "ogg" ### Example ```rust Decoder::builder() .with_hint("mp3") ``` ``` -------------------------------- ### Error Handling with Match Pattern Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Demonstrates handling potential errors during file opening and audio decoding using `match` statements, providing specific error messages. ```rust fn play_audio_with_fallback(filename: &str) { let file = match File::open(filename) { Ok(f) => f, Err(e) => { eprintln!("Cannot open file: {}", e); return; } }; let source = match Decoder::try_from(file) { Ok(s) => s, Err(e) => { eprintln!("Cannot decode: {}", e); return; } }; } ``` -------------------------------- ### Enable Recording Feature in Cargo.toml Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Shows the Cargo.toml configuration required to enable the `recording` feature for microphone support. ```toml [dependencies] rodio = { version = "0.22", features = ["recording"] } ``` -------------------------------- ### Open Default Audio Output Device Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Opens the default audio output device, with automatic fallback to alternative devices and configurations if the default fails. ```rust pub fn open_default_sink() -> Result ``` -------------------------------- ### Create Mixer and MixerSource Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Creates a new mixer and its corresponding source. Specify the desired output channel count and sample rate. ```rust pub fn mixer(channels: ChannelCount, sample_rate: SampleRate) -> (Mixer, MixerSource) ``` -------------------------------- ### Add Multiple Audio Files to Mixer Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/mixer-and-sink.md Demonstrates adding two different audio files (MP3 and OGG) to a mixer, which will then play them simultaneously. ```rust use std::fs::File; use rodio::{Decoder, mixer::mixer}; let (mixer, source) = mixer(nz!(2), nz!(48_000)); let file1 = File::open("music1.mp3")?; let decoder1 = Decoder::try_from(file1)?; mixer.add(decoder1); let file2 = File::open("music2.ogg")?; let decoder2 = Decoder::try_from(file2)?; mixer.add(decoder2); // Both play simultaneously ``` -------------------------------- ### Enable Recording Feature for Microphone Access Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/errors.md Illustrates the need to enable the `recording` feature for microphone access and shows the compilation error if it's missing. ```rust // This won't compile without the "recording" feature use rodio::microphone::MicrophoneBuilder; // ERROR: module not found ``` -------------------------------- ### Create a source from an iterator Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/types.md FromIter allows creating an audio source directly from any iterator that yields audio samples. Use the `from_iter` constructor. ```rust pub struct FromIter { ... } // Constructor example: from_iter(iter: I) ``` -------------------------------- ### Correct Frame Alignment for Stereo SamplesBuffer Source: https://github.com/rustaudio/rodio/blob/master/_autodocs/api-reference/buffers-and-queues.md Illustrates the correct way to provide sample data for a stereo SamplesBuffer, ensuring the sample count is even to align with stereo frames. Incorrect alignment can lead to audio glitches or panics. ```rust // CORRECT: 4 samples for stereo (2 frames) let samples = vec![0.0, 0.0, 0.5, 0.5]; // L, R, L, R let buffer = SamplesBuffer::new(nz!(2), nz!(44100), samples); // INCORRECT: 5 samples for stereo (incomplete frame) let bad_samples = vec![0.0, 0.0, 0.5, 0.5, 0.0]; // Missing R channel // Will cause glitches or panics ```