HTML Audio
In HTML, you can embed audio files into web pages using the <audio>
element. This element allows you to add audio files such as MP3, WAV, and OGG to your web pages.
Here’s an example of how to use the <audio>
element:
html
<audio controls> <source src="music.mp3" type="audio/mp3"> <source src="music.ogg" type="audio/ogg"> Your browser does not support the audio tag. </audio>
In the example above, we’ve used the controls
attribute to add controls for the audio player, such as play, pause, and volume controls. We’ve also included two sources: one for the MP3 format and another for the OGG format. The browser will automatically choose the appropriate source depending on the browser’s capabilities.
Attributes for the <audio>
element:
src
: Specifies the URL of the audio filecontrols
: Adds audio player controls (play, pause, volume, etc.)autoplay
: Automatically starts playing the audio fileloop
: Loops the audio filemuted
: Mutes the audiopreload
: Specifies if and how the audio file should be loaded when the page loads (e.g.,preload="none"
,preload="metadata"
, orpreload="auto"
)
Methods, Properties, and Events:
The <audio>
element also provides methods, properties, and events to interact with the audio player. Here are some of the most commonly used ones:
Methods:
play()
: Starts playing the audiopause()
: Pauses the audioload()
: Loads the audio file
Properties:
currentTime
: Gets or sets the current position (in seconds) of the audio playbackduration
: Gets the duration (in seconds) of the audio filevolume
: Gets or sets the volume (between 0 and 1) of the audio playbackpaused
: Gets or sets whether the audio is currently paused
Events:
onplay
: Fires when the audio starts playingonpause
: Fires when the audio is pausedonended
: Fires when the audio has ended
Here’s an example of how to use some of these methods, properties, and events:
html
<audio id="myAudio" controls> <source src="music.mp3" type="audio/mp3"> <source src="music.ogg" type="audio/ogg"> Your browser does not support the audio tag. </audio> <script> var audio = document.getElementById("myAudio"); audio.play(); audio.volume = 0.5; audio.onended = function() { alert("The audio has ended"); }; </script>
In the example above, we’ve added an id
attribute to the <audio>
element so that we can reference it in JavaScript. We then use the play()
method to start playing the audio, the volume
property to set the volume to 50%, and the onended
event to show an alert message when the audio has ended.
Overall, the <audio>
element provides a simple way to add audio files to your web pages and provides methods, properties, and events for interacting with the audio player.