HTML Audio

      Comments Off on HTML Audio
Spread the love

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 file
  • controls: Adds audio player controls (play, pause, volume, etc.)
  • autoplay: Automatically starts playing the audio file
  • loop: Loops the audio file
  • muted: Mutes the audio
  • preload: Specifies if and how the audio file should be loaded when the page loads (e.g., preload="none", preload="metadata", or preload="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 audio
  • pause(): Pauses the audio
  • load(): Loads the audio file

Properties:

  • currentTime: Gets or sets the current position (in seconds) of the audio playback
  • duration: Gets the duration (in seconds) of the audio file
  • volume: Gets or sets the volume (between 0 and 1) of the audio playback
  • paused: Gets or sets whether the audio is currently paused

Events:

  • onplay: Fires when the audio starts playing
  • onpause: Fires when the audio is paused
  • onended: 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.