Help for play mp3 file with Rust Wasm Webaudio

I want to play an mp3 file from Rust Wasm.
I would like to use Webaudio.
I found an example how to make an FM oscilator:

But there is nothing about playing an mp3 file.
I should first prepare a buffer from the file and then give it to Webaudio. But I don’t know how to do it.
Please, help.

In general, unless there is some dedicated frontend in stdweb or gloo, basically what you can do in a browser is the same as in javascript thanks to js-sys and web-sys crates. These will expose all web apis to rust. They are unergonomic to use, but the idea is to build more idiomatic frontends for all web apis in gloo.

TL;DR If you can do it in javascript, you can do it in rust

I use this code now in javascript:
var audio = new Audio(‘content/sound/mem_sound_02.mp3’);;
How could I write this in Rust?

My project is here:

Well, looking over the Web Audio Api on MDN I can’t find an interface called just Audio, so I don’t really understand how that would work in javascript, but if you look at the interfaces on that page, say AudioBuffer, than the equivalent in rust wasm would be here in web-sys.

I found the true name of the object and it is supported in web-sys:

Thank you very much.

Glad you found it. Be warned, web-sys is not an ergonomic interface

I It works:
let result = web_sys::HtmlAudioElement::new_with_src(“content/sound/mem_sound_01.mp3”);

But I get a warning:

The compiler warns me:
warning: unused std::result::Result that must be used
–> src\
20 | result.unwrap().play();
| ^^^^^^^^^^^^^^^^^^^^^^^
= note: #[warn(unused_must_use)] on by default
= note: this Result may be an Err variant, which should be handled

Probably is about handling JSValue and probably it contains a Promise. What can be done here?

I made a quick working example here:

Result is explained in the book:

The mdn docs say it’s a promise which can throw 2 exceptions.

I have never used it, but the docs for web-sys have a promise rejection event.

You will have to dig a bit. There is also a crate wasm-bindgen-futures, which lets you convert a promise into a rust future I think…

If all else fails, there is a chat room of the wasm workgroup on discord and there is the issue tracker for web-sys, but as I said, it’s not ergonomic right now, as it’s automatically generated bindings to javascript.

Thank you.
I didn’t realize that play() returns Result.
I was fixated all the time on web_sys::HtmlAudioElement::new() constructor and expected that there is the problem in that Result.
For now I will just unwrap the Result of play(). I have only a learning experimental code. Later I will see if I understand something more about the JSValue and Promise. I need to find a similar code somewhere to see how it works. I cannot solve it on my own with the documentation.
Your help was great !

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.