Skip to main content

play_spatial_sound/
play_spatial_sound.rs

1use rg3d_core::futures::executor::block_on;
2use rg3d_sound::{
3    algebra::{Point3, UnitQuaternion, Vector3},
4    buffer::{DataSource, SoundBufferResource},
5    context::SoundContext,
6    engine::SoundEngine,
7    pool::Handle,
8    source::{generic::GenericSourceBuilder, spatial::SpatialSourceBuilder, SoundSource, Status},
9};
10use std::{
11    thread,
12    time::{self, Duration},
13};
14
15fn main() {
16    // Initialize sound engine with default output device.
17    let engine = SoundEngine::new();
18
19    // Initialize new sound context.
20    let context = SoundContext::new();
21
22    engine.lock().unwrap().add_context(context.clone());
23
24    // Load sound buffer.
25    let drop_buffer = SoundBufferResource::new_generic(
26        block_on(DataSource::from_file("examples/data/drop.wav")).unwrap(),
27    )
28    .unwrap();
29
30    // Create spatial source - spatial sources can be positioned in space.
31    let source = SpatialSourceBuilder::new(
32        GenericSourceBuilder::new()
33            .with_buffer(drop_buffer)
34            .with_looping(true)
35            .with_status(Status::Playing)
36            .build()
37            .unwrap(),
38    )
39    .build_source();
40
41    // Each sound sound must be added to context, context takes ownership on source
42    // and returns pool handle to it by which it can be accessed later on if needed.
43    let source_handle: Handle<SoundSource> = context.state().add_source(source);
44
45    // Move sound around listener for some time.
46    let start_time = time::Instant::now();
47    let mut angle = 0.0f32;
48    while (time::Instant::now() - start_time).as_secs() < 11 {
49        if let SoundSource::Spatial(spatial) = context.state().source_mut(source_handle) {
50            let axis = Vector3::y_axis();
51            let rotation_matrix =
52                UnitQuaternion::from_axis_angle(&axis, angle.to_radians()).to_homogeneous();
53            spatial.set_position(
54                rotation_matrix
55                    .transform_point(&Point3::new(0.0, 0.0, 3.0))
56                    .coords,
57            );
58        }
59        angle += 3.6;
60
61        // Limit rate of updates.
62        thread::sleep(Duration::from_millis(100));
63    }
64}