mod decoder;
pub mod generator;
use decoder::MorseDecoder;
pub use generator::MorseGenerator;
use anyhow::Result;
pub fn decode_wav_file<P: AsRef<std::path::Path>>(path: P) -> Result<String> {
use hound::{SampleFormat, WavReader};
let mut reader = WavReader::open(path)?;
let spec = reader.spec();
if spec.sample_format != SampleFormat::Int && spec.sample_format != SampleFormat::Float {
anyhow::bail!(
"Unsupported sample format: {:?}. Only 16-bit Int and 32-bit Float are supported.",
spec.sample_format
);
}
let mut decoder = MorseDecoder::new(spec.sample_rate, 12000)?;
let samples_f32: Vec<f32> = if spec.sample_format == SampleFormat::Int {
reader
.samples::<i16>()
.map(|s| s.unwrap() as f32 / 32768.0)
.collect()
} else {
reader.samples::<f32>().map(|s| s.unwrap()).collect()
};
let mono_samples: Vec<f32> = if spec.channels > 1 {
samples_f32
.chunks_exact(spec.channels as usize)
.map(|chunk| chunk.iter().sum::<f32>() / spec.channels as f32)
.collect()
} else {
samples_f32
};
const CHUNK_SIZE: usize = 4096;
for chunk in mono_samples.chunks(CHUNK_SIZE) {
decoder.process(chunk)?;
}
decoder.finalize()
}
pub fn decode_samples(samples: &[f32], sample_rate: u32) -> Result<String> {
let mut decoder = MorseDecoder::new(sample_rate, 12000)?;
const CHUNK_SIZE: usize = 4096;
for chunk in samples.chunks(CHUNK_SIZE) {
decoder.process(chunk)?;
}
decoder.finalize()
}