1 // Hound -- A wav encoding and decoding library in Rust
2 // Copyright (C) 2017 Ruud van Asseldonk
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // A copy of the License has been included in the root of the repository.
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12
13 // This example computes the root mean square (rms) of an audio file with
14 // integer or float samples, of at most 32 bits per sample. It is a slightly
15 // more elaborate version of the example found in the readme, mostly useful for
16 // checking whether Hound can read a specific file.
17
18 extern crate hound;
19
20 use std::env;
21 use std::io;
22
23 /// Compute the RMS of either integers or float samples.
compute_rms<S, R>(reader: &mut hound::WavReader<R>) -> f64 where f64: From<S>, S: hound::Sample, R: io::Read,24 fn compute_rms<S, R>(reader: &mut hound::WavReader<R>) -> f64
25 where
26 f64: From<S>,
27 S: hound::Sample,
28 R: io::Read,
29 {
30 let sqr_sum = reader.samples::<S>().fold(0.0, |sqr_sum, s| {
31 let sample = f64::from(s.unwrap());
32 sqr_sum + sample * sample
33 });
34 (sqr_sum / reader.len() as f64).sqrt()
35 }
36
main()37 fn main() {
38 // Compute the RMS for all files given on the command line.
39 for fname in env::args().skip(1) {
40 let mut reader = hound::WavReader::open(&fname).unwrap();
41 let rms = match reader.spec().sample_format {
42 hound::SampleFormat::Float => compute_rms::<f32, _>(&mut reader),
43 hound::SampleFormat::Int => compute_rms::<i32, _>(&mut reader),
44 };
45 println!("{}: {:0.1} ({} samples)", fname, rms, reader.len());
46 }
47 }
48