HTML audio
Created By: chatGPT
To use HTML audio, you can utilize the
<audio>
element, which allows you to embed sound content in your web pages. This element supports various audio formats such as MP3, WAV, and OGG. You can include attributes like controls to display the audio controls such as play, pause, and volume adjustment.<audio controls>
<source src="audio-file.mp3" type="audio/mpeg">
<source src="audio-file.ogg" type="audio/ogg">
Your browser does not support the audio tag.
</audio>
If you want to automatically play the audio without showing the controls, you can use the autoplay and hidden attributes. Note that autoplay may not work on all devices due to user experience policies.
<audio autoplay hidden>
<source src="audio-file.mp3" type="audio/mpeg">
</audio>
You may also want to set the audio to loop when it finishes playing using the loop attribute. This is useful for background music or sound effects that should repeat indefinitely.
<audio controls loop>
<source src="audio-file.mp3" type="audio/mpeg">
</audio>
In addition to basic usage, you can use JavaScript to control the audio programmatically, such as dynamically playing or pausing the audio based on specific events.
const audioElement = document.querySelector('audio');
audioElement.play(); // To play the audio
audioElement.pause(); // To pause the audio
Lastly, keep in mind that for a better user experience, always provide a fallback message within the
<audio>
element that informs users if their browser does not support audio playback.<audio controls>
<source src="audio-file.mp3" type="audio/mpeg">
<source src="audio-file.ogg" type="audio/ogg">
<p>Your browser does not support the audio tag.</p>
</audio>