1 // Hound -- A wav encoding and decoding library in Rust
2 // Copyright 2018 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 appends one second of a 440 Hz sine wave to the file "sine.wav".
14 // If the file does not exist, it is created instead.
15
16 use std::f32::consts::PI;
17 use std::i16;
18 use std::path::Path;
19
20 extern crate hound;
21
main()22 fn main() {
23 let spec = hound::WavSpec {
24 channels: 1,
25 sample_rate: 44100,
26 bits_per_sample: 16,
27 sample_format: hound::SampleFormat::Int,
28 };
29
30 let path: &Path = "sine.wav".as_ref();
31
32 let mut writer = match path.is_file() {
33 true => hound::WavWriter::append(path).unwrap(),
34 false => hound::WavWriter::create(path, spec).unwrap(),
35 };
36
37 // We should not append blindly, we should make sure that the existing file
38 // has the right spec, because that is what we assume when writing.
39 assert_eq!(spec, writer.spec());
40
41 println!("Old duration is {} seconds.", writer.duration() / spec.sample_rate);
42
43 for t in (0 .. 44100).map(|x| x as f32 / 44100.0) {
44 let sample = (t * 440.0 * 2.0 * PI).sin();
45 let amplitude = i16::MAX as f32;
46 writer.write_sample((sample * amplitude) as i16).unwrap();
47 }
48
49 println!("New duration is {} seconds.", writer.duration() / spec.sample_rate);
50
51 writer.finalize().unwrap();
52 }
53