javascript

How to use JavaScript and HTML5 to play Sounds / Audio files.

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:

 

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.

Related Posts

Leave a Reply