Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update noise.rs #24

Merged
merged 2 commits into from
Oct 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion knyst/src/gen/noise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use super::GenState;
use crate as knyst;
use crate::Sample;

/// Whate noise (fastrand RNG based on wyrand)
/// White noise (fastrand RNG based on wyrand)
pub struct WhiteNoise {
rng: fastrand::Rng,
}
Expand Down Expand Up @@ -98,3 +98,39 @@ impl PinkNoise {
GenState::Continue
}
}

/// Brown noise (also known as red noise)
///
/// Brown noise is generated by integrating white noise.
/// This implementation uses a simple integration of white noise samples with a small step size,
/// and clamps the output to prevent it from exceeding the [-1.0, 1.0] range.
pub struct BrownNoise {
rng: fastrand::Rng,
last_output: Sample,
}

#[impl_gen(range = normal)]
impl BrownNoise {
#[allow(missing_docs)]
pub fn new() -> Self {
let mut rng = fastrand::Rng::new();
rng.seed(next_randomness_seed());
Self {
rng,
last_output: 0.0,
}
}

#[allow(missing_docs)]
pub fn process(&mut self, output: &mut [Sample]) -> GenState {
for out in output.iter_mut() {
let white = self.rng.f32() as Sample * 2.0 - 1.0;
// Adjust the coefficient to control the step size
self.last_output += white * 0.1;
// Clamp to [-1.0, 1.0] to prevent output from exceeding the range
self.last_output = self.last_output.clamp(-1.0, 1.0);
*out = self.last_output;
}
GenState::Continue
}
}
Loading