Html 5 Audio

Introduction

Before HTML5, there was no standard way to embed video into web pages.

Until now, multimedia content on the Web has been placed in web pages by means of third-party plugins or applications that integrate with the web browser. (QuickTime, RealPlayer, and Silverlight.)

The most popular way to embed video and audio on web pages is by means of Adobe’s Flash Player plugin.

The introduction of the video and audio elements in HTML5 resolves this problem and makes multimedia a seamless part of a web page, the same as the img element.

With HTML5, there’ s no need for the user to download third-party software to view your content, and the video or audio player is easily accessible via scripting.

Adding HTML5 Audio

To play native audio on your web page. Add the audio element, with the src attribute referencing the file location of your audio file and fallback content for older browsers:

snippet
<audio controls>
    <source src="audio.ogg">
        <source src="audio.mp3">
            Download <a href="audio.ogg">episode 42 of Learning to Love HTML5</a>
</audio>
controls attribute

Add 'controls' attribute if you want browsers to display a default control interface for your audio.

Audio Codecs
File TypeDescription
.aacLossy compression scheme developed as an improvement over MP3, with similar bit rates but better sound quality. Google’s open, royalty-free media format, which relies on the Vorbis audio codec for compression.
.mp3Patented yet popular format, which uses lossy compression to achieve file sizes one-tenth of non-compressed.
.oggAn open source alternative to .mp3 that also uses a lossy compression format.
.wavProprietary format for audio that does not utilize any compression.
.webmGoogle’s open, royalty-free media format, which relies on the Vorbis audio codec for compression.
Integrating Multiple Sources

HTML5 enable us to declare multiple audio files in your HTML5 audio.

snippet
<audio controls>
    <source src="audio.ogg">
        <source src="audio.mp3">
            Download <a href="audio.ogg">episode 42 of Learning to Love HTML5</a>
</audio>
Note
When using the source element in audio, the src attribute is dropped.
Preloading the Audio

audio has several attributes that allow you to configure your audio implementation.

The preload attribute allows to hint to the browser when it should begin buffering the audio. preload is used to optimize the download process. Currently has limited browser support.

<audio controls preload>

There are three preload values.

ValuesDescription
preload="auto"It leaves the action up to the browser. If it is a mobile situation or a slow connection, the browser can decide not to preload in order to save bandwidth.
preload="metadata"Tells the browser not to buffer the audio itself until the user activates the controls but metadata like duration and tracks should be preloaded.
preload="none"Tells the browser that not to buffer the audio itself until the user activates the controls.
Creating Fallback Content

Fallback simply means that if a users browser doesn’t support HTML5 audio, it instead displays the fallback content. For these users you could include fallback Flash.

snippet
<audio controls>
    <source src="audio.ogg">
        <source src="audio.mp3">
            <object data="player.swf?audio=audio.mp3">
                <param name="movie" value="player.swf?audio=audio.mp3"> Video and Flash 
                                            are not supported by your browser.
            </object>
</audio>

You could also include a download link for audio as a fallback content.

snippet
<audio controls>
    <source src="audio.ogg">
        <source src="audio.mp3">
            Your browser doesn't support HTML5 audio. You should upgrade. download <a href="audio">Download</a>.
</audio>
--

Manipulating the Audio Stream

Html5 enable us to control and manipulate how your HTML5 audio plays in the browser. There are few attributes in audio that give us control over your playback.

PropertiesDescription
autoplayTells the browser to start playing the audio as soon as the page loads.
loopLoop tells the browser to loop the audio when playing forwards.

Like controls, both autoplay and loop are Boolean attributes, so you simply include them in the opening audio tag when you want them.

<audio controls loop>

<audio controls autoplay>
--

Custom controls using Java Script

If you want more control that these basic attributes (autoplay and loop), you can create custom controls using Java Script.

audio and video have attributes, events and methods you can manipulate with Java-Script.
MethodsDescription
canplaytype(type)Whether the browser can play a particular type of media
currentTimeThe current playback position denoted in seconds
durationThe length of the audio file in seconds
play()Start playback at the current position
pause()Pause playback if the audio is actively playing
Example

The following code allows the user to jump to specific time on a audio file.

snippet
<audio>
    <source src="audio.ogg">
        <source src="audio.mp3">
</audio>
<button title="Play at 30 seconds" onclick="playAt(30);">30 seconds</button>
<script>
    function playAt(seconds) {
        var audio = document.getElementsByTagName("audio")[0];
        audio.currentTime = seconds;
        audio.play();
    }
</script>
Example

There is no stop method. To stop use the pause method to to return to the beginning of the audio file via currentTime.

Note
when creating your own custom controls, drop the controls Boolean attribute from audio.

Generate audio using JavaScript

You can generate audio on the browser without the src attribute or source elements by using methods defined by the Mozilla Audio Data API

It has limited support. Only Firefox 4+ and Chrome Beta currently support it.

MethodsDescription
mozSetup(channels, sampleRate)Defines the channels and sample rate for the generated audio stream
mozWriteAudio(buffer)Writes the samples, from an array, for the generated audio
mozCurrentSampleOffset()Gets the current playback position of the audio, denoted in samples

Visualizing audio Using canvas

We can create a visualization of your HTML5 audio using canvas.

snippet
<audio src="audio.ogg"></audio>
<canvas width="512" height="100"></canvas>
<button title="Generate Waveform" onclick="genWave();">Generate Waveform</button>
<script>
    function genWave() {
        var audio = document.getElementsByTagName("audio")[0];
        var canvas = document.getElementsByTagName("canvas")[0];
        var context = canvas.getContext('2d');
        audio.addEventListener("MozAudioAvailable", buildWave, false);

        function buildWave(event) {
            var channels = audio.mozChannels;
            var frameBufferLength = audio.mozFrameBufferLength;
            var fbData = event.frameBuffer;
            var stepInc = (frameBufferLength / channels) / canvas.width;
            var waveAmp = canvas.height / 2;
            canvas.width = canvas.width;
            context.beginPath();
            context.moveTo(0, waveAmp - fbData[0] * waveAmp);
            for (var i = 1; i < canvas.width; i++) {
                context.lineTo(i, waveAmp - fbData[i * stepInc] * waveAmp);
            }
            context.strokeStyle = "#fff";
            context.stroke();
        }
        audio.play();
    }
</script>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +