Handle all the different wav formats correctly

This commit is contained in:
Gwilym Kuiper 2021-10-17 22:37:50 +01:00
parent 58262bf0f5
commit 292c4fd20f

View file

@ -15,7 +15,7 @@ pub fn include_wav(input: TokenStream) -> TokenStream {
let include_path = path.to_string_lossy(); let include_path = path.to_string_lossy();
let mut wav_reader = hound::WavReader::open(&path) let wav_reader = hound::WavReader::open(&path)
.unwrap_or_else(|_| panic!("Failed to load file {}", include_path)); .unwrap_or_else(|_| panic!("Failed to load file {}", include_path));
assert_eq!( assert_eq!(
@ -24,9 +24,7 @@ pub fn include_wav(input: TokenStream) -> TokenStream {
"agb currently only supports sample rate of 10512Hz" "agb currently only supports sample rate of 10512Hz"
); );
let samples = wav_reader let samples = samples_from_reader(wav_reader);
.samples::<i8>()
.map(|sample| sample.unwrap() as u8);
let result = quote! { let result = quote! {
{ {
@ -40,3 +38,24 @@ pub fn include_wav(input: TokenStream) -> TokenStream {
TokenStream::from(result) TokenStream::from(result)
} }
fn samples_from_reader<'a, R>(reader: hound::WavReader<R>) -> Box<dyn Iterator<Item = u8> + 'a>
where
R: std::io::Read + 'a,
{
let bitrate = reader.spec().bits_per_sample;
let reduction = bitrate - 8;
match reader.spec().sample_format {
hound::SampleFormat::Float => Box::new(
reader
.into_samples::<f32>()
.map(|sample| (sample.unwrap() * (i8::MAX as f32)) as u8),
),
hound::SampleFormat::Int => Box::new(
reader
.into_samples::<i32>()
.map(move |sample| (sample.unwrap() >> reduction) as u8),
),
}
}