MyInternships.in

HTML Audio & Video

HTML DOM Audio Object

The Audio object represents an HTML <audio> element and exposes the HTMLAudioElement interface. You can grab one from an existing element with getElementById() or build a brand new one entirely in JavaScript with the new Audio() constructor.


Definition and Usage

An Audio object gives JavaScript full control over sound: loading a source, starting and stopping playback, adjusting volume and speed, and reacting to events. Because it inherits every member of HTMLMediaElement, it supports properties like currentTime, duration and volume, methods like play(), pause() and load(), and events like play, pause and ended.

The new Audio() constructor returns an HTMLAudioElement that is not attached to the page. Since it is not in the DOM tree it shows no controls, which makes it perfect for sound effects, notification tones and background music you trigger programmatically.

Syntax

// Create a brand-new audio element in JavaScript
let sound = new Audio(url);

// Or access an existing <audio> element already on the page
let audio = document.getElementById("myAudio");

The url argument is optional. When provided it sets the src property of the new audio element so the browser can begin loading the file.

Example

This complete page creates an Audio object in JavaScript, plays it on a button click, and reports its state in an output box. Paste it into the editor and press Run.

A sound effect created and controlled purely in JavaScript
Example
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Audio Object Demo</title>
</head>
<body>
  <h2>Sound created with new Audio()</h2>

  <button onclick="playSound()">Play</button>
  <button onclick="pauseSound()">Pause</button>
  <button onclick="showState()">Show state</button>

  <p id="output">Press Play to start.</p>

  <script>
    // Build the audio purely in JavaScript (no <audio> tag needed)
    const sound = new Audio("https://www.w3schools.com/html/horse.mp3");
    sound.volume = 0.6; // 0.0 to 1.0
    const out = document.getElementById("output");

    function playSound() {
      // play() returns a Promise; catch it in case autoplay is blocked
      sound.play()
        .then(() => out.textContent = "Playing at volume " + sound.volume)
        .catch(err => out.textContent = "Blocked: " + err.message);
    }

    function pauseSound() {
      sound.pause();
      out.textContent = "Paused at " + sound.currentTime.toFixed(1) + "s";
    }

    function showState() {
      out.textContent = "paused=" + sound.paused +
        ", currentTime=" + sound.currentTime.toFixed(1) + "s";
    }

    // React to the built-in media events
    sound.addEventListener("ended", () => out.textContent = "Finished!");
  </script>
</body>
</html>

More Examples

Because the Audio object supports the full media API, you can wire multiple sound effects and play them on demand without cluttering your HTML.

Reusing one Audio object for a repeatable sound effect
Example
<!DOCTYPE html>
<html>
<body>
  <button onclick="ping()">Play tone</button>
  <p id="log"></p>

  <script>
    const tone = new Audio("https://www.w3schools.com/html/horse.mp3");
    const log = document.getElementById("log");

    tone.addEventListener("play",  () => log.textContent = "Started");
    tone.addEventListener("pause", () => log.textContent = "Paused");
    tone.addEventListener("ended", () => log.textContent = "Done");

    function ping() {
      tone.currentTime = 0; // rewind so rapid clicks re-trigger it
      tone.play().catch(e => log.textContent = e.message);
    }
  </script>
</body>
</html>

Common Members

NameDescription
new Audio(url)Constructor that creates a new HTMLAudioElement, optionally with a source URL
play()Starts or resumes playback and returns a Promise
pause()Pauses playback of the audio
srcGets or sets the URL of the audio file
volumeGets or sets the volume from 0.0 to 1.0
currentTimeGets or sets the current playback position in seconds
pausedReturns whether the audio is currently paused
ended (event)Fires when playback reaches the end of the audio
⚠️

Most browsers require a user gesture (such as a click) before audio may play with sound. Calling play() without one causes the returned Promise to reject with a NotAllowedError, which is why the examples always .catch() it.

Key Takeaways

  • The Audio object implements HTMLAudioElement and inherits all HTMLMediaElement members.
  • new Audio(url) builds an audio element in JavaScript with no markup and no visible controls.
  • play() returns a Promise; always .catch() it to handle blocked autoplay.
  • Set volume (0.0 to 1.0), read currentTime and paused, and listen for play, pause and ended events.
  • Reset currentTime = 0 to replay a sound effect on rapid, repeated triggers.

Related HTML Topics

Keep learning with these closely related tutorials.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships