Skip to main content

raw_streaming/
raw_streaming.rs

1use rg3d_sound::{
2    buffer::{DataSource, RawStreamingDataSource, SoundBufferResource},
3    context::SoundContext,
4    engine::SoundEngine,
5    source::{generic::GenericSourceBuilder, Status},
6};
7use std::{thread, time::Duration};
8
9#[derive(Debug)]
10struct SamplesGenerator {
11    sample_rate: usize,
12    frequency: f32,
13    amplitude: f32,
14    index: usize,
15}
16
17impl SamplesGenerator {
18    pub fn new() -> Self {
19        Self {
20            sample_rate: 44100,
21            frequency: 440.0,
22            amplitude: 0.75,
23            index: 0,
24        }
25    }
26}
27
28impl Iterator for SamplesGenerator {
29    type Item = f32;
30
31    fn next(&mut self) -> Option<Self::Item> {
32        let sample = self.amplitude
33            * ((2.0 * std::f32::consts::PI * self.index as f32 * self.frequency)
34                / self.sample_rate as f32)
35                .sin();
36
37        self.index += 1;
38
39        Some(sample)
40    }
41}
42
43impl RawStreamingDataSource for SamplesGenerator {
44    fn sample_rate(&self) -> usize {
45        self.sample_rate
46    }
47
48    fn channel_count(&self) -> usize {
49        1
50    }
51}
52
53fn main() {
54    // Initialize sound engine with default output device.
55    let engine = SoundEngine::new();
56
57    // Initialize new sound context.
58    let context = SoundContext::new();
59
60    engine.lock().unwrap().add_context(context.clone());
61
62    // Create sine wave generator
63    let sine_wave = DataSource::RawStreaming(Box::new(SamplesGenerator::new()));
64
65    let sine_wave_buffer = SoundBufferResource::new_streaming(sine_wave).unwrap();
66
67    // Create generic source (without spatial effects) using that buffer.
68    let source = GenericSourceBuilder::new()
69        .with_buffer(sine_wave_buffer)
70        .with_status(Status::Playing)
71        .build_source()
72        .unwrap();
73
74    context.state().add_source(source);
75
76    // Play sound for some time.
77    thread::sleep(Duration::from_secs(10));
78}