Playing Sound with React

Tiempo de lectura: < 1 minuto

Today we are going to implement a function that will allow us to play sound using React.

The first thing we need to do is to create this function that will allow us to load the sound:

export function loadSound(source: string) {
    const sound = document.createElement("audio");
    sound.src = source;
    sound.setAttribute("preload", "auto");
    sound.setAttribute("controls", "none");
    sound.style.display = "none"; // <-- hidden
    document.body.appendChild(sound);
    return sound;
}

And to use it, we will do the following.

We place our sounds inside assets/sounds

We import them and call the created function putting .start() at the end.

import my_sound from 'assets/sounds/my_sound.mp3';

const sound = loadSound(my_sound);
sound.play();

Leave a Comment