Skip to main content

raw_samples/
raw_samples.rs

1use rg3d_sound::engine::SoundEngine;
2use rg3d_sound::{
3    buffer::{DataSource, SoundBufferResource},
4    context::SoundContext,
5    source::{generic::GenericSourceBuilder, Status},
6};
7use std::{thread, time::Duration};
8
9fn main() {
10    // Initialize sound engine with default output device.
11    let engine = SoundEngine::new();
12
13    // Initialize new sound context.
14    let context = SoundContext::new();
15
16    engine.lock().unwrap().add_context(context.clone());
17
18    // Create sine wave.
19    let sample_rate = 44100;
20    let sine_wave = DataSource::Raw {
21        sample_rate,
22        channel_count: 1,
23        samples: {
24            let frequency = 440.0;
25            let amplitude = 0.75;
26            (0..44100)
27                .map(|i| {
28                    amplitude
29                        * ((2.0 * std::f32::consts::PI * i as f32 * frequency) / sample_rate as f32)
30                            .sin()
31                })
32                .collect()
33        },
34    };
35
36    let sine_wave_buffer = SoundBufferResource::new_generic(sine_wave).unwrap();
37
38    // Create generic source (without spatial effects) using that buffer.
39    let source = GenericSourceBuilder::new()
40        .with_buffer(sine_wave_buffer)
41        .with_status(Status::Playing)
42        .with_looping(true)
43        .build_source()
44        .unwrap();
45
46    context.state().add_source(source);
47
48    // Play sound for some time.
49    thread::sleep(Duration::from_secs(10));
50}