TExcelTAD
Home › HTML › HTML Audio

HTML Audio

The <audio> element plays sound — music, podcasts, sound effects, voice recordings — directly in the browser. It works almost exactly like <video>, just without a picture.

The basic <audio> element

html
<audio controls>
  <source src="song.ogg" type="audio/ogg">
  <source src="song.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>
  • controls shows the player (play button, timeline, volume).
  • The browser tries each <source> in order and uses the first format it can play.
  • Text inside the element is fallback content for very old browsers.

Without controls, the audio element is invisible — it can still be played from JavaScript, which is how games add sound effects.

Note: ExcelTAD playgrounds run offline, so there are no audio files to load. Below you will see an empty player, and then sound generated on the fly with the Web Audio API so you can still hear something.

Audio attributes

Attribute Effect
controls Show the playback controls
autoplay Try to start immediately (usually blocked unless the user has interacted with the page)
muted Start silent
loop Repeat forever
preload none, metadata or auto — how much to download in advance
src Single source file (alternative to <source> children)

What the player looks like

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <p>A player with no real file behind it:</p>
  <audio controls>
    <source src="missing-song.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
  </audio>
  <p>Each browser draws its own style of player; you cannot restyle the built-in controls much, but you can hide them and build your own.</p>
</body>
</html>

Audio formats

Format MIME type Notes
MP3 audio/mpeg Universal support — the safe default
AAC / M4A audio/mp4 Good quality, wide support
Ogg Vorbis / Opus audio/ogg Open formats, good compression
WAV audio/wav Uncompressed — large files, good for short effects

Controlling audio with JavaScript

The audio element shares the media API with video: play(), pause(), currentTime, volume, loop, and events like ended. A typical custom button looks like this:

html
<audio id="ding" src="ding.mp3" preload="auto"></audio>
<button onclick="document.getElementById('ding').play()">Ring the bell</button>

Making sound without a file

The Web Audio API can synthesise sound directly. It is more advanced than <audio>, but it lets us hear a real tone in this sandbox. Browsers only allow sound after a user gesture, which is why the tone starts from a button click.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <button id="beep">Play a 440 Hz tone</button>
  <button id="chord">Play a little tune</button>
  <p id="msg"></p>
  <script>
    let ctx = null;
    function getContext() {
      const AC = window.AudioContext || window.webkitAudioContext;
      if (!AC) { document.getElementById('msg').textContent = 'Web Audio is not supported here.'; return null; }
      if (!ctx) ctx = new AC();
      return ctx;
    }
    function tone(freq, start, length) {
      const c = getContext();
      if (!c) return;
      const osc = c.createOscillator();
      const gain = c.createGain();
      osc.frequency.value = freq;
      gain.gain.setValueAtTime(0.2, c.currentTime + start);
      gain.gain.exponentialRampToValueAtTime(0.001, c.currentTime + start + length);
      osc.connect(gain).connect(c.destination);
      osc.start(c.currentTime + start);
      osc.stop(c.currentTime + start + length);
    }
    document.getElementById('beep').onclick = function () { tone(440, 0, 0.6); };
    document.getElementById('chord').onclick = function () {
      [262, 330, 392, 523].forEach(function (f, i) { tone(f, i * 0.25, 0.4); });
    };
  </script>
</body>
</html>

Tip: Keep the volume low when generating sound — the gain of 0.2 above is deliberately quiet.

A custom player for an <audio> element

Here is a pattern you would use with a real file: hide the default controls and drive the element with your own buttons. With no file present, the status line reports the problem instead of failing silently.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <audio id="track" preload="none">
    <source src="podcast-episode-1.mp3" type="audio/mpeg">
  </audio>
  <button id="toggle">▶ Play</button>
  <span id="state">Ready</span>
  <script>
    const track = document.getElementById('track');
    const btn = document.getElementById('toggle');
    const state = document.getElementById('state');
    btn.onclick = function () {
      if (track.paused) {
        track.play().then(function () {
          btn.textContent = '⏸ Pause';
          state.textContent = 'Playing';
        }).catch(function () {
          state.textContent = 'Could not load the audio file (expected in this sandbox).';
        });
      } else {
        track.pause();
        btn.textContent = '▶ Play';
        state.textContent = 'Paused';
      }
    };
  </script>
</body>
</html>

Good practice

  • Do not autoplay sound. Let the user choose to start it.
  • Provide a transcript for spoken audio such as podcasts so deaf users and searchers can read it (see Media Accessibility).
  • Offer at least one widely supported format (MP3).
  • Use preload="none" for long files the user might never play, to save their data.

Test yourself

What happens to an <audio> element without the controls attribute?

  1. It cannot play at all
  2. It is invisible but can still be played from JavaScript
  3. It plays automatically
  4. It shows a download link

Which MIME type matches an MP3 file?

  1. audio/mp3
  2. audio/mpeg
  3. audio/ogg
  4. video/mp4

Why did the Web Audio example start sound from a button click?

  1. Buttons are faster
  2. Browsers only allow audio to start after a user gesture
  3. Web Audio needs a form
  4. It is required by HTML syntax