阿里云主机折上折
  • 微信号
Current Site:Index > The usage and attributes of the '<audio>' tag

The usage and attributes of the '<audio>' tag

Author:Chuan Chen 阅读数:39895人阅读 分类: HTML

The <audio> tag is a core element in HTML5 for embedding audio content, supporting multiple audio formats and playback controls. Through attribute configuration, it enables interactive features such as autoplay, looping, and preloading, while compatibility handling and JavaScript APIs extend more complex audio manipulation scenarios.

Basic Syntax of the <audio> Tag

The default structure of the <audio> tag is as follows:

<audio src="audio.mp3"></audio>

This is the simplest example of audio embedding, but in practice, control bars or other attributes are usually added:

<audio src="audio.mp3" controls></audio>

Without the controls attribute, the audio will not display any interface elements, requiring JavaScript to control playback.

Core Attributes Explained

src and <source> Child Element

Use the src attribute to specify a single audio source:

<audio src="audio.ogg" controls></audio>

However, to ensure compatibility across browsers, it is recommended to use the <source> child element to provide multiple format options:

<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
  Your browser does not support the audio element.
</audio>

The browser will detect the first playable format from top to bottom, with the final text serving as a fallback message.

controls Attribute

Adding this attribute displays the browser's default control bar:

<audio src="audio.mp3" controls></audio>

The control bar typically includes play/pause, progress bar, volume, and fullscreen (on some browsers) controls. Styles vary by browser:

  • Chrome: Gray theme with an orange progress bar
  • Firefox: Blue theme
  • Safari: Dark gray minimalist style

autoplay Attribute

Automatically plays the audio, but most modern browsers block autoplay with sound:

<audio src="audio.mp3" autoplay></audio>

Requires interaction or the muted attribute to work:

<button onclick="document.getElementById('player').play()">Play</button>
<audio id="player" src="audio.mp3"></audio>

loop Attribute

Enables loop playback mode:

<audio src="bgmusic.mp3" loop controls></audio>

Suitable for background music, but note: looping may increase battery drain on mobile devices.

preload Attribute

Controls audio preloading behavior, with options:

<audio src="largefile.mp3" preload="auto"></audio>
  • auto (default): Loads metadata and partial data
  • metadata: Loads only metadata (e.g., duration)
  • none: No preloading

On mobile networks, metadata is recommended to save data.

muted Attribute

Initial mute state, often used with autoplay:

<audio src="advertisement.mp3" autoplay muted></audio>

Users can manually unmute after interaction.

Advanced JavaScript Control

Use the DOM API for precise control:

Basic Playback Control

<audio id="player" src="sound.mp3"></audio>
<button onclick="document.getElementById('player').play()">Play</button>
<button onclick="document.getElementById('player').pause()">Pause</button>

Volume Control

const audio = document.getElementById('player');
audio.volume = 0.5; // Range: 0.0 to 1.0

Seeking

audio.currentTime = 30; // Jump to 30 seconds

Event Listeners

audio.addEventListener('ended', () => {
  console.log('Playback ended');
});
audio.addEventListener('timeupdate', () => {
  console.log(`Current progress: ${audio.currentTime}`);
});

Custom Styling Example

Override the default control bar by hiding native controls and implementing your own:

<audio id="custom-player" src="music.mp3"></audio>
<div class="custom-controls">
  <button class="play-btn">▶</button>
  <input type="range" class="progress" min="0" max="100" value="0">
</div>

<style>
  .custom-controls {
    display: flex;
    align-items: center;
    width: 300px;
  }
  .progress {
    flex-grow: 1;
    margin: 0 10px;
  }
</style>

<script>
  const player = document.getElementById('custom-player');
  const playBtn = document.querySelector('.play-btn');
  const progress = document.querySelector('.progress');

  playBtn.addEventListener('click', () => {
    if (player.paused) {
      player.play();
      playBtn.textContent = '❚❚';
    } else {
      player.pause();
      playBtn.textContent = '▶';
    }
  });

  player.addEventListener('timeupdate', () => {
    progress.value = (player.currentTime / player.duration) * 100;
  });

  progress.addEventListener('input', () => {
    player.currentTime = (progress.value / 100) * player.duration;
  });
</script>

Compatibility Handling Tips

Fallback Format Strategy

Ensure at least MP3 and OGG formats are provided:

<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
  <!-- Ultimate fallback -->
  <embed src="audio.mp3" width="300" height="90" type="audio/mpeg">
</audio>

Feature Detection

Check browser support via JavaScript:

if (typeof Audio !== 'undefined') {
  const audio = new Audio();
  if (audio.canPlayType('audio/mpeg')) {
    console.log('MP3 supported');
  }
} else {
  console.warn('Browser does not support HTML5 Audio');
}

Mobile-Specific Handling

User Interaction Restrictions

Platforms like iOS require playback to be triggered by user gestures:

document.addEventListener('click', () => {
  const audio = new Audio('notification.mp3');
  audio.play(); // Only works within click events
}, { once: true });

Low-Power Mode

Listen for pause events during long playback:

audio.addEventListener('pause', (e) => {
  if (e.target.paused && e.target.currentTime > 0) {
    console.log('Possibly paused by the system');
  }
});

Audio Visualization Extension

Combine with Web Audio API for spectrum analysis:

<audio id="visualizer" src="dance.mp3" controls></audio>
<canvas id="canvas" width="600" height="200"></canvas>

<script>
  const audio = document.getElementById('visualizer');
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');

  const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  const analyser = audioCtx.createAnalyser();
  const source = audioCtx.createMediaElementSource(audio);
  
  source.connect(analyser);
  analyser.connect(audioCtx.destination);
  analyser.fftSize = 256;

  const bufferLength = analyser.frequencyBinCount;
  const dataArray = new Uint8Array(bufferLength);

  function draw() {
    requestAnimationFrame(draw);
    analyser.getByteFrequencyData(dataArray);
    
    ctx.fillStyle = 'rgb(0, 0, 0)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    const barWidth = (canvas.width / bufferLength) * 2.5;
    let x = 0;
    
    for(let i = 0; i < bufferLength; i++) {
      const barHeight = dataArray[i] / 2;
      ctx.fillStyle = `rgb(${barHeight+100}, 50, 50)`;
      ctx.fillRect(x, canvas.height-barHeight, barWidth, barHeight);
      x += barWidth + 1;
    }
  }

  audio.addEventListener('play', () => {
    audioCtx.resume().then(() => {
      draw();
    });
  });
</script>

Performance Optimization Strategies

Audio Sprite Technique

Combine multiple short audio clips into a single file and play by timestamp:

function playSprite(audio, start, duration) {
  audio.currentTime = start;
  audio.play();
  setTimeout(() => audio.pause(), duration * 1000);
}

const sfx = document.getElementById('sfx-pack');
playSprite(sfx, 12.5, 0.8); // Play 0.8s audio starting at 12.5s

Lazy Loading

Load audio only when scrolled into view:

const lazyAudio = document.querySelector('audio[data-src]');
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.src = entry.target.dataset.src;
      observer.unobserve(entry.target);
    }
  });
});
observer.observe(lazyAudio);

Server Configuration Notes

Ensure the server sends correct MIME types:

# Nginx configuration example
location ~* \.(mp3|ogg|wav)$ {
  add_header Access-Control-Allow-Origin *;
  types {
    audio/mpeg mp3;
    audio/ogg ogg;
    audio/wav wav;
  }
}

Common Issue Solutions

Audio Sync Issues

Use readyState to check playable status:

audio.addEventListener('canplaythrough', () => {
  // Ensure sufficient data is loaded
  audio.play().catch(e => console.error(e));
});

Decoding Error Handling

Capture media error events:

audio.addEventListener('error', () => {
  switch(audio.error.code) {
    case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
      console.error('Format not supported');
      break;
    case MediaError.MEDIA_ERR_DECODE:
      console.error('Decoding error');
      break;
  }
});

Live Streaming Support

Handle live streams with MediaSource Extensions:

<audio id="live-stream"></audio>

<script>
  const audio = document.getElementById('live-stream');
  const mediaSource = new MediaSource();
  
  audio.src = URL.createObjectURL(mediaSource);
  
  mediaSource.addEventListener('sourceopen', () => {
    const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
    fetch('live-stream.php')
      .then(response => response.arrayBuffer())
      .then(data => {
        sourceBuffer.appendBuffer(data);
      });
  });
</script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.