Today we are going to implement a function that will allow us to play sound using React.
![](https://i0.wp.com/images.pexels.com/photos/18016895/pexels-photo-18016895/free-photo-of-camara-fotografia-vintage-dispositivo.jpeg?w=1200&ssl=1)
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();
![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/07/cropped-light_logo-5.png?resize=100%2C100&ssl=1)