A quick table and descriptions of useful attributes:
Attribute | Description |
src | The URL to the audio file |
duration | The length, in seconds, of the track. You will get trailing decimals for the exact length of the track (it's not rounded off) |
paused | True if playback is paused, false otherwise |
autoplay | When set to true, the track will automatically start playing when enough of the track has loaded |
controls | When set to true, a control widget is rendered on the HTML page |
Here's an audio tag that isn't hooked up to anything, but has the controls enabled:
Useful methods:
Method | Description |
play() | Starts audio playback |
pause() | Pauses audio playback |
Note that there is no stop() function. However, I think this is a reasonable way to mimic stop:
function stop(audioElement) {
audioElement.pause();
audioElement.currentTime = 0;
}
Useful events:
Event | Description |
play | Called when the audio track begins playing |
pause | Called when the audio track is paused |
ended | Called when the audio track has ended |
Here's a code snippet instantiating an audio element using Javascript:
// Create an <audio> element dynamically.
var audio = new Audio();
audio.src = 'file.m4a';
audio.controls = true;
audio.addEventListener('play', function() { isPlaying = true; }, false);
audio.addEventListener('pause', function() { isPlaying = false; }, false);
audio.addEventListener('ended', function() { isPlaying = false; }, false);
document.body.appendChild(audio);
In this example, I create an audio tag with a source file pointing locally to "file.m4a". Controls are enabled and visible when the page is rendered. I also add 3 event handlers that simply toggle a state variable that shows whether the track is playing or not.
This scratches the surface of what you can do with HTML5 <audio>. Later, I'll get into tying <audio> with the AudioContext object for sound mixing (filters, panning, gain, etc.) and visualization (frequency and amplitude graphing). Think of this as the tiny tip of a very, very large iceberg.
No comments:
Post a Comment