show fft in terminal
All checks were successful
Build legacy Nix package on Ubuntu / build (push) Successful in 4m25s

This commit is contained in:
2025-01-12 18:21:15 +01:00
parent 86dfbd21f4
commit d4bfd03c02
3 changed files with 79 additions and 4 deletions

View File

@ -1,4 +1,4 @@
use std::{thread::sleep, time::Duration};
use std::{sync::mpsc, thread::sleep, time::Duration};
use color_eyre::eyre::bail;
use cpal::{
@ -6,7 +6,11 @@ use cpal::{
BufferSize, HostId, SupportedBufferSize,
};
use log::{debug, error, info, trace};
use rustfft::{num_complex::Complex, FftPlanner};
use rustfft::{
num_complex::{Complex, ComplexFloat},
FftPlanner,
};
use textplots::{Chart, Plot, Shape};
fn main() -> color_eyre::Result<()> {
env_logger::init();
@ -44,6 +48,7 @@ fn main() -> color_eyre::Result<()> {
let fft = planner.plan_fft_forward(buffer_size as usize);
let mut fft_data = vec![Complex::new(0.0, 0.0); buffer_size as usize];
let mut fft_scratch = vec![Complex::new(0.0, 0.0); buffer_size as usize];
let (sender, receiver) = mpsc::channel();
let stream = device.build_input_stream(
&config,
@ -51,7 +56,15 @@ fn main() -> color_eyre::Result<()> {
for i in 0..data.len() {
fft_data[i] = Complex::new(data[i], 0.0);
}
fft.process_with_scratch(&mut fft_data[..], &mut fft_scratch[..]);
let mut fft_output = vec![Complex::new(0.0, 0.0); data.len()];
fft.process_outofplace_with_scratch(
&mut fft_data[..],
&mut fft_output[..],
&mut fft_scratch[..],
);
if let Err(e) = sender.send(fft_output) {
error!("Unable to send fft output: {e}");
}
},
|err| {
error!("input stream error: {err}");
@ -62,6 +75,14 @@ fn main() -> color_eyre::Result<()> {
stream.play()?;
loop {
sleep(Duration::from_secs(1));
let data = receiver.recv()?;
let plot_data: Vec<_> = data
.into_iter()
.enumerate()
.map(|(i, datum)| ((i as f32).log10(), datum.abs() / 1024.0.sqrt()))
.collect();
Chart::new_with_y_range(200, 50, 0.0, 1024.0.log10(), 0.0, 2.0)
.lineplot(&Shape::Bars(&plot_data[..]))
.display();
}
}