To play sounds in JavaScript, you can use the HTML5 Audio API. Here is a basic example of how to use it to play a sound:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <title>Play Sound in JavaScript</title> </head> <body> <button onclick="playSound()">Play Sound</button> <script> function playSound() { var audio = new Audio('sound.mp3'); audio.play(); } </script> </body> </html> |
In this example, we have an HTML button with an onclick
event that calls the playSound()
function when clicked. The playSound()
function creates a new Audio
object with the path to the sound file, and then calls the play()
method to play the sound.
You can replace 'sound.mp3'
with the path to your own sound file, such as 'https://yourdomain.com/sound.mp3'
.
Note that not all browsers support all audio formats. You may need to provide multiple audio formats (e.g. MP3, OGG, WAV) to ensure compatibility across different browsers.