feat: ✨ hear from microphone
This commit is contained in:
parent
2cd01c08c8
commit
0f34554797
6 changed files with 100 additions and 0 deletions
58
src/gui.rs
Normal file
58
src/gui.rs
Normal file
|
@ -0,0 +1,58 @@
|
|||
use leptos::{
|
||||
IntoView, ev,
|
||||
html::{ElementChild, button},
|
||||
logging::log,
|
||||
prelude::{OnAttribute, Read, Show, ShowProps, ToChildren},
|
||||
server::LocalResource,
|
||||
task::spawn_local,
|
||||
};
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
use web_sys::{
|
||||
HtmlAudioElement, MediaStream, MediaStreamConstraints,
|
||||
wasm_bindgen::{JsCast, JsValue},
|
||||
window,
|
||||
};
|
||||
|
||||
pub fn app() -> impl IntoView {
|
||||
let audio_stream = LocalResource::new(|| media());
|
||||
let props = ShowProps::builder()
|
||||
.when(move || audio_stream.read().is_some())
|
||||
.children(ToChildren::to_children(move || {
|
||||
let audio_element = HtmlAudioElement::new().unwrap();
|
||||
let audio_stream = audio_stream.read();
|
||||
let audio_stream = audio_stream.as_deref();
|
||||
audio_element.set_src_object(audio_stream);
|
||||
button()
|
||||
.on(ev::click, move |_| match audio_element.play() {
|
||||
Ok(audio_element_play_promise) => {
|
||||
log!("{}", "Play will");
|
||||
spawn_local(async move {
|
||||
JsFuture::from(audio_element_play_promise).await.ok();
|
||||
});
|
||||
log!("{}", "Play must");
|
||||
}
|
||||
Err(err_val) => log!("{:#?}", err_val),
|
||||
})
|
||||
.child("Happy Button")
|
||||
.into_view()
|
||||
}))
|
||||
.fallback(|| button().child("Sad Button"))
|
||||
.build();
|
||||
Show(props)
|
||||
}
|
||||
|
||||
async fn media() -> MediaStream {
|
||||
let media_devices = window().unwrap().navigator().media_devices().unwrap();
|
||||
let constraints = MediaStreamConstraints::new();
|
||||
constraints.set_audio(&JsValue::TRUE);
|
||||
let media_stream_promise = media_devices
|
||||
.get_user_media_with_constraints(&constraints)
|
||||
.unwrap();
|
||||
let media_stream = JsFuture::from(media_stream_promise)
|
||||
.await
|
||||
.unwrap()
|
||||
.dyn_into::<MediaStream>()
|
||||
.unwrap();
|
||||
let audio_tracks = media_stream.get_audio_tracks();
|
||||
MediaStream::new_with_tracks(&audio_tracks).unwrap()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue