|
| 1 | +#![allow(clippy::needless_return)] |
| 2 | +//! Audio demo that plays the bundled "slash" OGG Vorbis fixture. |
| 3 | +//! |
| 4 | +//! This demo validates that `SoundBuffer` decoding and audio output playback |
| 5 | +//! can be composed together using only the `lambda-rs` API surface. |
| 6 | +
|
| 7 | +use std::{ |
| 8 | + sync::{ |
| 9 | + atomic::{ |
| 10 | + AtomicUsize, |
| 11 | + Ordering, |
| 12 | + }, |
| 13 | + Arc, |
| 14 | + }, |
| 15 | + time::Duration, |
| 16 | +}; |
| 17 | + |
| 18 | +use lambda::audio::{ |
| 19 | + AudioOutputDeviceBuilder, |
| 20 | + SoundBuffer, |
| 21 | +}; |
| 22 | + |
| 23 | +fn main() { |
| 24 | + const SLASH_VORBIS_STEREO_48000_OGG: &[u8] = include_bytes!(concat!( |
| 25 | + env!("CARGO_MANIFEST_DIR"), |
| 26 | + "/../../crates/lambda-rs-platform/assets/audio/slash_vorbis_stereo_48000.ogg" |
| 27 | + )); |
| 28 | + |
| 29 | + let buffer = |
| 30 | + SoundBuffer::from_ogg_bytes(SLASH_VORBIS_STEREO_48000_OGG).unwrap(); |
| 31 | + |
| 32 | + let cursor = Arc::new(AtomicUsize::new(0)); |
| 33 | + let buffer = Arc::new(buffer); |
| 34 | + |
| 35 | + let cursor_for_callback = cursor.clone(); |
| 36 | + let buffer_for_callback = buffer.clone(); |
| 37 | + |
| 38 | + let _device = AudioOutputDeviceBuilder::new() |
| 39 | + .with_label("play-sound") |
| 40 | + .with_sample_rate(buffer.sample_rate()) |
| 41 | + .with_channels(buffer.channels()) |
| 42 | + .build_with_output_callback(move |writer, _info| { |
| 43 | + let writer_channels = writer.channels() as usize; |
| 44 | + let writer_frames = writer.frames(); |
| 45 | + |
| 46 | + writer.clear(); |
| 47 | + |
| 48 | + if writer_channels == 0 { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + let write_samples = writer_frames.saturating_mul(writer_channels); |
| 53 | + let start = |
| 54 | + cursor_for_callback.fetch_add(write_samples, Ordering::Relaxed); |
| 55 | + |
| 56 | + let source_samples = buffer_for_callback.samples(); |
| 57 | + |
| 58 | + for frame in 0..writer_frames { |
| 59 | + for channel in 0..writer_channels { |
| 60 | + let sample_index = start |
| 61 | + .saturating_add(frame.saturating_mul(writer_channels)) |
| 62 | + .saturating_add(channel); |
| 63 | + let value = source_samples.get(sample_index).copied().unwrap_or(0.0); |
| 64 | + writer.set_sample(frame, channel, value); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return; |
| 69 | + }) |
| 70 | + .unwrap(); |
| 71 | + |
| 72 | + std::thread::sleep(Duration::from_secs_f32(buffer.duration_seconds() + 0.20)); |
| 73 | + drop(_device); |
| 74 | + return; |
| 75 | +} |
0 commit comments