Skip to content

Commit ec88396

Browse files
committed
Implement AudioWorkletNode message passing from render to control
1 parent ac28a2f commit ec88396

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

examples/worklet_message_port.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl AudioWorkletProcessor for WhiteNoiseProcessor {
7575
_inputs: &'b [&'a [&'a [f32]]],
7676
outputs: &'b mut [&'a mut [&'a mut [f32]]],
7777
_params: AudioParamValues<'_>,
78-
_scope: &RenderScope,
78+
scope: &RenderScope,
7979
) -> bool {
8080
// edit the output buffer in place
8181
outputs[0].iter_mut().for_each(|buf| {
@@ -93,6 +93,10 @@ impl AudioWorkletProcessor for WhiteNoiseProcessor {
9393
})
9494
});
9595

96+
if scope.current_frame % 12800 == 0 {
97+
scope.post_message(Box::new(scope.current_frame));
98+
}
99+
96100
true // tail time, source node will always be active
97101
}
98102

@@ -125,6 +129,12 @@ fn main() {
125129
// connect to speakers
126130
noise.node().connect(&context.destination());
127131

132+
// add event handling for the heartbeat events from the render thread
133+
noise.node().port().set_onmessage(|m| {
134+
let frame = m.downcast::<u64>().unwrap();
135+
println!("rendered frame {frame}");
136+
});
137+
128138
// enjoy listening
129139
println!("White noise");
130140
std::thread::sleep(std::time::Duration::from_secs(2));

src/render/processor.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,18 @@ impl std::fmt::Debug for RenderScope {
3838
}
3939

4040
impl RenderScope {
41+
/// Send a message to the corresponding AudioWorkletNode of this processor
42+
///
43+
/// This method is just a shim of the full
44+
/// [`MessagePort`](https://webaudio.github.io/web-audio-api/#dom-audioworkletprocessor-port)
45+
/// `onmessage` functionality of the AudioWorkletProcessor.
46+
pub fn post_message(&self, msg: Box<dyn Any + Send + 'static>) {
47+
if let Some(sender) = self.event_sender.as_ref() {
48+
// sending could fail if the channel is saturated or the main thread is shutting down
49+
let _ = sender.try_send(EventDispatch::message(self.node_id.get(), msg));
50+
}
51+
}
52+
4153
pub(crate) fn send_ended_event(&self) {
4254
if let Some(sender) = self.event_sender.as_ref() {
4355
// sending could fail if the channel is saturated or the main thread is shutting down

0 commit comments

Comments
 (0)