Skip to content

Commit

Permalink
Custom output stream config example
Browse files Browse the repository at this point in the history
  • Loading branch information
PetrGlad committed Nov 21, 2024
1 parent 95060b1 commit 678df03
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions examples/custom_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use cpal::traits::HostTrait;
use cpal::{BufferSize, SampleFormat, SampleRate};
use rodio::source::SineWave;
use rodio::Source;
use std::error::Error;
use std::thread;
use std::time::Duration;

fn main() -> Result<(), Box<dyn Error>> {
// You can use any other output device that can be queried from CPAL.
let default_device = cpal::default_host()
.default_output_device()
.ok_or("No default audio output device is found.")?;
let stream_handle = rodio::OutputStreamBuilder::from_device(default_device)?
// No need to set all parameters explicitly here,
// the defaults were set from the device's description.
.with_buffer_size(BufferSize::Fixed(256))
.with_sample_rate(SampleRate(48_000))
.with_sample_format(SampleFormat::F32)
// Note that the function below still tries alternative configs if the specified one fails.
// If you need to only use the exact specified configuration,
// then use OutputStreamBuilder::open_stream() instead.
.try_open_stream()?;
let mixer = stream_handle.mixer();

let wave = SineWave::new(740.0)
.amplify(0.1)
.take_duration(Duration::from_secs(1));
mixer.add(wave);

println!("Beep...");
thread::sleep(Duration::from_millis(1500));

Ok(())
}

0 comments on commit 678df03

Please sign in to comment.