HTML Audio
HTML Audio is a built-in feature in the HTML language that allows you to embed audio content directly into a web page. It enables you to add audio files to your web page and control the playback of the audio through the use of HTML tags and JavaScript.
To add audio to your web page, you can use the <audio>
tag.
As an example:
<audio src="music.mp3" controls>
Your browser does not support the audio element.
</audio>
In this example:
- The
"music.mp3"
is the source file for the audio, and the"controls"
attribute is added to enable the built-in audio controls. - The text
"Your browser does not support the audio element."
will be displayed if the browser does not support the audio element. - You can also use JavaScript to control the playback of the audio, such as starting, pausing, or stopping the audio.
HTML Audio Muted
Here's an example of how you can use the muted attribute in the <audio>
tag to mute the audio by default:
<audio src="music.mp3" controls muted>
Your browser does not support the audio element.
</audio>
In this example:
- The muted attribute is added to the
<audio>
tag to mute the audio by default. - The controls attribute is also added to enable the built-in audio controls in the browser.
HTML Audio with javascript
To play audio in HTML using JavaScript, you can use the HTML5 audio
element, which allows you to embed audio content in web pages.
As an example:
<audio id="myAudio" src="sound.mp3"></audio>
<button onclick="playAudio()">Play Audio</button>
<script>
function playAudio() {
var audio = document.getElementById("myAudio");
audio.play();
}
</script>
In this example:
- The
audio
element is given an id of"myAudio"
and asrc
attribute pointing to the sound file to be played ("sound.mp3"
). - The
playAudio()
function is called when the button is clicked and uses thegetElementById()
method to get a reference to the audio element. - The
play()
method is then called on the audio element to start playing the sound.
You can also use the pause()
to pause the audio, currentTime
to set the playback position, and volume
to adjust the volume.
As an example:
<audio id="myAudio" src="sound.mp3"></audio>
<input
type="range"
min="0"
max="1"
step="0.1"
value="1"
oninput="setVolume(this.value)"
/>
<button onclick="playAudio()">Play Audio</button>
<script>
function playAudio() {
var audio = document.getElementById("myAudio");
audio.play();
}
function setVolume(vol) {
var audio = document.getElementById("myAudio");
audio.volume = vol;
}
</script>