-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio.rs
59 lines (55 loc) · 2.01 KB
/
audio.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
use futures_util::StreamExt;
use wsdom::{js_types::JsValue, Browser};
pub async fn app(browser: Browser) {
// create the UI
let document = wsdom::dom::document(&browser);
let body = document.get_body();
let btn1 = document.create_element(&"button", &wsdom::undefined());
let btn2 = document.create_element(&"button", &wsdom::undefined());
btn1.set_inner_text(
&"play t-rex sound with Audio() (make sure you don't have autoplay blocked)",
);
btn2.set_inner_text(&"play 440 Hz with WebAudio OscillatorNode");
body.append_child(&btn1);
body.append_child(&btn2);
// prepare the audio
let trex_audio = wsdom::dom::Audio(
&browser,
&Some(&"https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"),
);
let context = wsdom::dom::AudioContext::new(&browser, &wsdom::undefined());
let oscillator = context.create_oscillator();
oscillator.get_frequency().set_value(&440);
oscillator.connect_with_destinationNode_output_input(
&context.get_destination(),
&wsdom::undefined(),
&wsdom::undefined(),
);
context.suspend();
oscillator.start(&wsdom::undefined());
// set up the click listener
let mut click_stream1 = {
let (callback, func) = wsdom::callback::new_callback::<JsValue>(&browser);
btn1.add_event_listener(&"click", &func, &wsdom::null());
callback
};
let mut click_stream2 = {
let (callback, func) = wsdom::callback::new_callback::<JsValue>(&browser);
btn2.add_event_listener(&"click", &func, &wsdom::null());
callback
};
// wait for click
loop {
tokio::select! {
_ = click_stream1.next() => {
trex_audio.set_current_time(&0.0);
trex_audio.play();
}
_ = click_stream2.next() => {
context.resume();
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
context.suspend();
}
}
}
}