Skip to content

Commit

Permalink
Added noise_generator example
Browse files Browse the repository at this point in the history
  • Loading branch information
iluvcapra committed Aug 11, 2024
1 parent 1eabb21 commit 84a008d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 10 deletions.
33 changes: 33 additions & 0 deletions examples/noise_generator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use std::thread;
use std::time::Duration;

use rodio::source::{pink, white, Source};

fn main() {
let (_stream, stream_handle) = rodio::OutputStream::try_default().unwrap();

let noise_duration = Duration::from_millis(1000);
let interval_duration = Duration::from_millis(1500);

stream_handle
.play_raw(
white(cpal::SampleRate(48000))
.amplify(0.1)
.take_duration(noise_duration),
)
.unwrap();
println!("Playing white noise");

thread::sleep(interval_duration);

stream_handle
.play_raw(
pink(cpal::SampleRate(48000))
.amplify(0.1)
.take_duration(noise_duration),
)
.unwrap();
println!("Playing pink noise");

thread::sleep(interval_duration);
}
27 changes: 17 additions & 10 deletions src/source/noise.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::Source;

use rand::prelude::*;
use super::SeekError;

/// Create a new white noise source.
#[inline]
Expand All @@ -18,16 +18,12 @@ pub fn pink(sample_rate: cpal::SampleRate) -> PinkNoise {
#[derive(Clone, Debug)]
pub struct WhiteNoise {
sample_rate: cpal::SampleRate,
rng: rand::rngs::ThreadRng,
}

impl WhiteNoise {
/// Create a new white noise generator.
pub fn new(sample_rate: cpal::SampleRate) -> Self {
Self {
sample_rate,
rng: rand::thread_rng(),
}
Self { sample_rate }
}
}

Expand All @@ -36,10 +32,9 @@ impl Iterator for WhiteNoise {

#[inline]
fn next(&mut self) -> Option<Self::Item> {
let ru32: i64 = self.rng.next_u32().into();
let scaled: i64 = 2 * ru32 - (u32::MAX / 2) as i64;
let sample: f32 = scaled as f32 / u32::MAX as f32;
Some(sample)
let randf = rand::random::<f32>();
let scaled = randf * 2.0 - 1.0;
Some(scaled)
}
}

Expand All @@ -63,6 +58,12 @@ impl Source for WhiteNoise {
fn total_duration(&self) -> Option<std::time::Duration> {
None
}

#[inline]
fn try_seek(&mut self, _: std::time::Duration) -> Result<(), SeekError> {
// Does nothing, should do nothing
Ok(())
}
}

// https://www.musicdsp.org/en/latest/Filters/76-pink-noise-filter.html
Expand Down Expand Up @@ -125,4 +126,10 @@ impl Source for PinkNoise {
fn total_duration(&self) -> Option<std::time::Duration> {
None
}

#[inline]
fn try_seek(&mut self, _: std::time::Duration) -> Result<(), SeekError> {
// Does nothing, should do nothing
Ok(())
}
}

0 comments on commit 84a008d

Please sign in to comment.