-
Notifications
You must be signed in to change notification settings - Fork 41
/
wasm.rs
74 lines (67 loc) · 1.69 KB
/
wasm.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::manager::backend::{Backend, Renderer};
use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
Device, Stream, StreamConfig,
};
use super::Error;
enum State {
Empty,
Uninitialized {
device: Device,
config: StreamConfig,
},
Initialized {
_stream: Stream,
},
}
/// A backend that uses [cpal](https://crates.io/crates/cpal) to
/// connect a [`Renderer`] to the operating system's audio driver.
pub struct CpalBackend {
state: State,
}
impl Backend for CpalBackend {
type Settings = ();
type Error = Error;
fn setup(_settings: Self::Settings) -> Result<(Self, u32), Self::Error> {
let host = cpal::default_host();
let device = host
.default_output_device()
.ok_or(Error::NoDefaultOutputDevice)?;
let config = device.default_output_config()?.config();
let sample_rate = config.sample_rate.0;
Ok((
Self {
state: State::Uninitialized { device, config },
},
sample_rate,
))
}
fn start(&mut self, mut renderer: Renderer) -> Result<(), Self::Error> {
if let State::Uninitialized { device, config } =
std::mem::replace(&mut self.state, State::Empty)
{
let channels = config.channels;
let stream = device.build_output_stream(
&config,
move |data: &mut [f32], _| {
renderer.on_start_processing();
for frame in data.chunks_exact_mut(channels as usize) {
let out = renderer.process();
if channels == 1 {
frame[0] = (out.left + out.right) / 2.0;
} else {
frame[0] = out.left;
frame[1] = out.right;
}
}
},
move |_| {},
)?;
stream.play()?;
self.state = State::Initialized { _stream: stream };
} else {
panic!("Cannot initialize the backend multiple times")
}
Ok(())
}
}