bbx_player/backend.rs
1use std::sync::{
2 Arc,
3 atomic::{AtomicBool, Ordering},
4};
5
6use crate::error::Result;
7
8/// Handle returned from `Player::play()` that allows stopping playback.
9pub struct PlayHandle {
10 stop_flag: Arc<AtomicBool>,
11}
12
13impl PlayHandle {
14 pub(crate) fn new(stop_flag: Arc<AtomicBool>) -> Self {
15 Self { stop_flag }
16 }
17
18 /// Stop playback.
19 pub fn stop(&self) {
20 self.stop_flag.store(true, Ordering::SeqCst);
21 }
22
23 /// Check if playback has been stopped.
24 pub fn is_stopped(&self) -> bool {
25 self.stop_flag.load(Ordering::SeqCst)
26 }
27}
28
29/// Trait for audio playback backends.
30///
31/// Backends receive an iterator of interleaved f32 samples and are
32/// responsible for sending them to the audio output device.
33pub trait Backend: Send + 'static {
34 /// Start playback of the given signal.
35 ///
36 /// This method consumes `self` (via `Box<Self>`) because backends
37 /// typically need to move ownership into a background thread.
38 fn play(
39 self: Box<Self>,
40 signal: Box<dyn Iterator<Item = f32> + Send>,
41 sample_rate: u32,
42 num_channels: u16,
43 stop_flag: Arc<AtomicBool>,
44 ) -> Result<()>;
45}