React + Rust + Wasm: Play an Audio File
In this article, we will use Bevy game engine in our React application from our Rust WASM library to play an audio file. We will build on the previous tutorial available here.
Run a Bevy App using Rust
Last time, we used a setup_3d
function with our Bevy app to render a 3D scene. Now, let's modify our lib.rs
to create another setup_audio
function that will play an audio file.
Update the setup function
#[wasm_bindgen]
pub fn run_bevy_app() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup_audio) # Defined below
.run();
}
Define setup_audio
fn setup_audio(
asset_server: Res<AssetServer>,
audio: Res<Audio>
) {
# ...
}
Read the file
fn setup_audio(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Please ensure that Windless Slopes.ogg is added to public/assets/sounds folder
let music = asset_server.load("sounds/Windless Slopes.ogg");
}
Play the file
fn setup_audio(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
# ...
audio.play(music);
}
Build the new wasm library
Let’s run wasm-pack again to build the updated library
wasm-pack build --target web
Call the function from the demo app
Finally, let’s add a button to load the wasm and call run_bevy_app
function from our App.ts
file like so:
// App.ts
import init, { run_bevy_app } from "rust-wasm-lib";
import './App.css';
function App() {
const runBevyApp = async () => {
await init();
run_bevy_app();
};
return (
<div className="App">
<button onClick={runBevyApp}>Run Bevy App</button>
</div>
);
}
export default App;
Now, if you run the updated app and click on Run Bevy App
, you should hear the music :)
If you liked this article, subscribe here to get the complete code and updates for the entire collection: