|
| 1 | +use crate::dependent_module; |
| 2 | +use wasm_bindgen::prelude::*; |
| 3 | +use wasm_bindgen::JsValue; |
| 4 | +use wasm_bindgen_futures::JsFuture; |
| 5 | +use web_sys::{AudioContext, AudioWorkletNode, AudioWorkletNodeOptions}; |
| 6 | + |
| 7 | +#[wasm_bindgen] |
| 8 | +struct WasmAudioProcessor(Box<dyn FnMut(&mut [f32]) -> bool>); |
| 9 | + |
| 10 | +#[wasm_bindgen] |
| 11 | +impl WasmAudioProcessor { |
| 12 | + pub fn process(&mut self, buf: &mut [f32]) -> bool { |
| 13 | + self.0(buf) |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +// Use wasm_audio if you have a single wasm audio processor in your application |
| 18 | +// whose samples should be played directly. |
| 19 | +pub async fn wasm_audio( |
| 20 | + process: Box<dyn FnMut(&mut [f32]) -> bool>, |
| 21 | +) -> Result<AudioContext, JsValue> { |
| 22 | + let ctx = AudioContext::new()?; |
| 23 | + prepare_wasm_audio(&ctx).await?; |
| 24 | + let node = wasm_audio_node(&ctx, process)?; |
| 25 | + node.connect_with_audio_node(&ctx.destination())?; |
| 26 | + Ok(ctx) |
| 27 | +} |
| 28 | + |
| 29 | +// wasm_audio_node creates an AudioWorkletNode running a wasm audio processor. |
| 30 | +// Remember to call prepare_wasm_audio once on your context before calling |
| 31 | +// this function. |
| 32 | +pub fn wasm_audio_node( |
| 33 | + ctx: &AudioContext, |
| 34 | + process: Box<dyn FnMut(&mut [f32]) -> bool>, |
| 35 | +) -> Result<AudioWorkletNode, JsValue> { |
| 36 | + AudioWorkletNode::new_with_options( |
| 37 | + &ctx, |
| 38 | + "WasmProcessor", |
| 39 | + &AudioWorkletNodeOptions::new().processor_options(Some(&js_sys::Array::of3( |
| 40 | + &wasm_bindgen::module(), |
| 41 | + &wasm_bindgen::memory(), |
| 42 | + &JsValue::from(WasmAudioProcessor(process)), |
| 43 | + ))), |
| 44 | + ) |
| 45 | +} |
| 46 | + |
| 47 | +pub async fn prepare_wasm_audio(ctx: &AudioContext) -> Result<(), JsValue> { |
| 48 | + nop(); |
| 49 | + let mod_url = dependent_module!("worklet_async.js")?; |
| 50 | + JsFuture::from(ctx.audio_worklet()?.add_module(&mod_url)?).await?; |
| 51 | + Ok(()) |
| 52 | +} |
| 53 | + |
| 54 | +// TextEncoder and TextDecoder are not available in Audio Worklets, but there |
| 55 | +// is a dirty workaround: Import polyfill.js to install stub implementations |
| 56 | +// of these classes in globalThis. |
| 57 | +#[wasm_bindgen(module = "/src/polyfill.js")] |
| 58 | +extern "C" { |
| 59 | + fn nop(); |
| 60 | +} |
0 commit comments