jmg049 / wavers

Rust library for reading and writing WAV files
MIT License
31 stars 6 forks source link

n_samples returns wrong number when converting between differently sized sample formats #9

Closed vkahl closed 1 year ago

vkahl commented 1 year ago

Reproducible example:

// The wav file behind fp is encoded with s16le sample format and contains
// one channel and 2048 samples. We are converting the samples to `f32`
// on the fly.
let wav: Wav<f32> = Wav::from_path(fp).unwrap();

// This fails!
assert!(wav.n_samples(), 2048);

// This succeeds, so n_samples is returning half the expected number.
assert!(wav.n_samples(), 1024);

I guess in the n_samples function, the total size of the data chunk is divided by the size of one sample after the conversion to f32. Since an f32 takes up twice as many bytes as i16, the outcome is half of the actual number of samples in the file.

jmg049 commented 1 year ago

Thanks.

I've seen this before but I thought I had fixed it. Will investigate.

jmg049 commented 1 year ago

Hey @vkahl , I've pushed the fix, thankfully very simple and straightforward. Thanks for catching it. I've also published V1.1.1 to crates.io

I've included a specific test case for this. I generated a random wav file, encoded as s161e and with 2048 samples. Then I open it as an f32 and check the number of samples is correct.

vkahl commented 1 year ago

Awesome, thanks a lot for the quick response and fix!