Skip to main content

write_wav/
write_wav.rs

1use rg3d_sound::engine::SoundEngine;
2use rg3d_sound::{
3    buffer::{DataSource, SoundBufferResource},
4    context::SoundContext,
5    pool::Handle,
6    source::{generic::GenericSourceBuilder, SoundSource, Status},
7};
8
9fn main() {
10    // Initialize sound engine without output device.
11    let engine = SoundEngine::without_device();
12
13    // Create new context.
14    let context = SoundContext::new();
15
16    // Register context in the engine.
17    engine.lock().unwrap().add_context(context.clone());
18
19    // Load sound buffer.
20    let door_open_buffer = SoundBufferResource::new_generic(
21        rg3d_sound::futures::executor::block_on(DataSource::from_file(
22            "examples/data/door_open.wav",
23        ))
24        .unwrap(),
25    )
26    .unwrap();
27
28    // Create generic source (without spatial effects) using that buffer.
29    let source = GenericSourceBuilder::new()
30        .with_buffer(door_open_buffer)
31        .with_status(Status::Playing)
32        .build_source()
33        .unwrap();
34
35    // Each sound sound must be added to context, context takes ownership on source
36    // and returns pool handle to it by which it can be accessed later on if needed.
37    let _source_handle: Handle<SoundSource> = context.state().add_source(source);
38
39    // Create output wav file. The sample rate is currently fixed.
40    let wav_spec = hound::WavSpec {
41        channels: 2,
42        sample_rate: rg3d_sound::context::SAMPLE_RATE,
43        bits_per_sample: 32,
44        sample_format: hound::SampleFormat::Float,
45    };
46    let mut wav_writer = hound::WavWriter::create("output.wav", wav_spec).unwrap();
47
48    // Create an output buffer.
49    let buf_len = SoundEngine::render_buffer_len();
50    let mut buf = vec![(0.0f32, 0.0f32); buf_len];
51    let mut samples_written = 0;
52
53    // Wait until sound will play completely.
54    while samples_written < 3 * rg3d_sound::context::SAMPLE_RATE {
55        engine.lock().unwrap().render(&mut buf);
56        for &(l, r) in buf.iter() {
57            wav_writer.write_sample(l).unwrap();
58            wav_writer.write_sample(r).unwrap();
59        }
60        samples_written += buf_len as u32;
61    }
62
63    wav_writer.finalize().unwrap();
64}