Skip to main content

play_sound/
play_sound.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};
8use std::{thread, time::Duration};
9
10fn main() {
11    // Initialize sound engine with default output device.
12    let engine = SoundEngine::new();
13
14    // Create new context.
15    let context = SoundContext::new();
16
17    // Register context in the engine.
18    engine.lock().unwrap().add_context(context.clone());
19
20    // Load sound buffer.
21    let door_open_buffer = SoundBufferResource::new_generic(
22        rg3d_sound::futures::executor::block_on(DataSource::from_file(
23            "examples/data/door_open.wav",
24        ))
25        .unwrap(),
26    )
27    .unwrap();
28
29    // Create generic source (without spatial effects) using that buffer.
30    let source = GenericSourceBuilder::new()
31        .with_buffer(door_open_buffer)
32        .with_status(Status::Playing)
33        .build_source()
34        .unwrap();
35
36    // Each sound sound must be added to context, context takes ownership on source
37    // and returns pool handle to it by which it can be accessed later on if needed.
38    let _source_handle: Handle<SoundSource> = context.state().add_source(source);
39
40    // Wait until sound will play completely.
41    thread::sleep(Duration::from_secs(3));
42}