Skip to content

Commit

Permalink
play around with dft
Browse files Browse the repository at this point in the history
  • Loading branch information
mark-i-m committed Sep 20, 2020
1 parent 0c60a62 commit 9e92590
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
61 changes: 61 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ edition = "2018"

[dependencies]
hound = "3.4.0"
rustfft = "3.0.1"
26 changes: 26 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,35 @@ fn main() {
let freq = compute_monotonic_freq(&buffer[(i * CHUNK_SIZE)..((i + 1) * CHUNK_SIZE)]);
let note = hz_to_note(freq);
println!("Estimated freq: {:0.0} Hz, {:?}", freq, note);
fft_stuff(&buffer[(i * CHUNK_SIZE)..((i + 1) * CHUNK_SIZE)]);
}
}

fn fft_stuff(buffer: &[i16]) {
use rustfft::{num_complex::Complex, num_traits::Zero, FFTplanner};

// Play around with FFT...
let mut buffer: Vec<_> = buffer
.iter()
.map(|re| Complex::new(*re as f32, 0.0))
.collect();
let mut fft_buffer = vec![Complex::zero(); buffer.len()];
let mut planner = FFTplanner::new(false);
let fft = planner.plan_fft(buffer.len());
fft.process(&mut buffer, &mut fft_buffer);

let len = fft_buffer.len();
let (i, _) = fft_buffer
.into_iter()
.take(len / 2)
.enumerate()
.map(|(i, v)| (i, v.norm().log10() * 20.0))
.max_by_key(|(_, v)| *v as usize)
.unwrap();
let freq = i as f64 * (SAMPLE_RATE as f64) / (len as f64);
println!(" {} Hz, {:?}", freq, hz_to_note(freq));
}

fn hz_to_note(freq: f64) -> Note {
fn f64_eq_ish(a: f64, b: f64) -> bool {
(a - b).abs() < NOTE_EPSILON
Expand Down

0 comments on commit 9e92590

Please sign in to comment.