Skip to content

Commit

Permalink
Add freq command
Browse files Browse the repository at this point in the history
  • Loading branch information
maxwellmattryan committed Oct 31, 2024
1 parent 23500e4 commit de050f5
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use async_trait::async_trait;

use crate::{
commands::{midi::MidiCommand, note::NoteCommand},
commands::{freq::FreqCommand, midi::MidiCommand, note::NoteCommand},
error::FNoteResult,
};

Expand All @@ -24,6 +24,9 @@ pub enum FNoteCommand {

/// Extracts the frequency and MIDI note number from a music note (e.g. C5).
Note(NoteCommand),

/// Extracts the (nearest) MIDI note number and music note from a frequency (e.g. 440).
Freq(FreqCommand),
}

#[async_trait]
Expand All @@ -32,6 +35,7 @@ impl Command for FNoteCommand {
match self {
Self::Midi(cmd) => cmd.run().await,
Self::Note(cmd) => cmd.run().await,
Self::Freq(cmd) => cmd.run().await,
}
}
}
58 changes: 58 additions & 0 deletions src/commands/freq.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use async_trait::async_trait;
use regex::Regex;

use crate::{
cli::Command,
commands::midi::{midi_note_number_to_frequency, midi_note_number_to_music_note},
error::{FNoteError, FNoteResult},
};

/// Extracts the (nearest) MIDI note number and music note from a frequency.
#[derive(structopt::StructOpt)]
pub struct FreqCommand {
/// The frequency to use.
#[structopt(parse(try_from_str = try_frequency_from_str))]
pub frequency: f32,
}

#[async_trait]
impl Command for FreqCommand {
async fn run(&self) -> FNoteResult<()> {
let midi_note_number = frequency_to_midi_note(self.frequency).unwrap();
let music_note = midi_note_number_to_music_note(midi_note_number).unwrap();

let frequency = midi_note_number_to_frequency(midi_note_number);
let difference = ((self.frequency - frequency) * 100.0).round() / 100.0;
let sign = if difference >= 0.0 { "+" } else { "-" };
let formatted_difference = if difference == 0.0 {
"".to_string()
} else {
format!(" ({}{}Hz)", sign, difference.abs())
};

println!("Frequency: {}Hz{}", frequency, formatted_difference);
println!("Note: {}", music_note);
println!("MIDI: {}", midi_note_number);

Ok(())
}
}

/// Converts a frequency to the nearest MIDI note number.
pub(crate) fn frequency_to_midi_note(frequency: f32) -> Option<u8> {
let midi_note = 69.0 + 12.0 * (frequency / 440.0).log2();
if (0..=127).contains(&(midi_note as u8)) {
Some(midi_note as u8)
} else {
None
}
}

fn try_frequency_from_str(arg: &str) -> FNoteResult<f32> {
let regex = Regex::new(r"^\d+(\.\d+)?$").unwrap();
if regex.is_match(arg) {
Ok(arg.parse::<f32>().unwrap())
} else {
Err(FNoteError::InvalidFrequency(arg.to_string()))
}
}
2 changes: 1 addition & 1 deletion src/commands/midi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl Command for MidiCommand {
"Note: {}",
midi_note_number_to_music_note(self.midi_note_number).unwrap()
);
println!("Frequency: {} Hz", midi_note_number_to_frequency(self.midi_note_number));
println!("Frequency: {}Hz", midi_note_number_to_frequency(self.midi_note_number));

Ok(())
}
Expand Down
1 change: 1 addition & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub(crate) mod freq;
pub(crate) mod midi;
pub(crate) mod note;
2 changes: 1 addition & 1 deletion src/commands/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl Command for NoteCommand {

println!("Note: {}", self.music_note);
println!("MIDI: {}", midi_note_number);
println!("Frequency: {} Hz", frequency);
println!("Frequency: {}Hz", frequency);

Ok(())
}
Expand Down
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ pub enum FNoteError {
#[error("Unknown command")]
UnknownCommand,

#[error("Invalid frequency \"{0}\"")]
InvalidFrequency(String),

#[error("Invalid MIDI note number \"{0}\"")]
InvalidMidiNoteNumber(String),

Expand Down

0 comments on commit de050f5

Please sign in to comment.