Html 5 Video

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.

HTML5’s new embedded content elements offers designers and developers more options for including media in our sites.

Similar in nature to audio, the video element shares many of the same attributes, have a similar syntax and can be styled and manipulated with CSS and JavaScript.

--

Adding HTML5 Video

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

<video src="video.ogv"></video>
preload attribute (Preloading the Video)

The preload attribute suggest to the browser whether and how it should download the video.

The preload attribute accepts one of three values

ValueDescription
autoauto indicates that the video and its associated metadata will start loading before the video is played.
nonenone indicates that the video shouldn’t load in the background before the user presses play.
metadataThis works like none, except that any metadata associated with the video (for example, its dimensions, duration, and the like) can be preloaded, even though the video itself won’t be.
<video src="video.ogv" controls preload></video>

You can skip the attribute and let the browser decide or give browsers a “hint” with specific values:

preload="auto" or, simply, preload
preload="metadata"
preload="none"
controls attribute

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

controls is a Boolean attribute, so no value is required. When the controls attribute is added to the video element, it tells the browser to make the controls visible and accessible to the user.

Each browser is responsible for the look of the built-in video controls. So these controls differ in appearance from browser to browser.

<video src="example.webm" width="375" height="280" controls></video>
poster Attribute (Placing a Image Placeholder)

When you view a video on the Web, normally a single frame of the video will display in order to provide a teaser(a frame of video) of its content. poster attribute makes easier to show the teaser.

The poster attribute points to an image that the browser will use while the video is downloading, or until the user tells the video to play. (This attribute is not applicable to <audio>.)

If we don’t use the poster attribute, the browser shows the first frame of the movie

<video src="example.webm" width="375" height="280" poster="teaser.jpg" controls></video>
audio Attribute

The audio attribute controls the default state of the audio track for the video element. This attribute has a value of muted.

Adding the muted vale will cause the video’s audio track to default to muted. It is only the default state. Interacting with the controls or javascript can change this.

<video src="example.webm" width="375" height="280" poster="teaser.jpg" audio="muted"></video>
autoplay Attribute

autoplay is Boolean attribute which tells the browser to start playing the video as soon as the page loads.

<video src="example.webm" width="375" height="280" controls autoplay>
</video>
loop attribute

loop is Boolean attribute which tells the browser to loop the video when playing forwards.

<video controls width="640" height="360" loop>
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogv" type="video/ogg" /> Your device does not support HTML5 video.
</video>
Video Codecs
ExtensionDescription
.mp4The container format for the proprietary H.264 codec that encodes video for a full range of devices, including high definition.
.ogvThe free, open source container format for the open source Theora codec. Results in lower quality than H.264.
.webmAnother open source container format, which is used by the new, royalty-free VP8 codec from Google.
Integrating Multiple Sources

HTML5 enable us to declare multiple video files in your HTML5 video. To include multiple video formats, add the source elements the video element so that every user agent to displays the video using the format of its choice.

When providing the source elements, there’s no need to specify a src for your video.

<video controls>
    <source src="video.mp4" />
    <source src="video.ogv" /> Your device does not support HTML5 video.
</video>
It is good practice to also specify the MIME type for your video files.
<source src="video.mp4" type="video/mp4" />
<source src="video.ogv" type="video/ogg" />
Since file formats are simply containers for different codecs, specify the compression used as below.
<source src="video.ogv" type="video/ogg; codecs='theora'">

The MIME type speeds up rendering of the video since it indicates what kind of content the browser is utilizing without the browser having to download a portion to make its own determination.

Here are some examples of MIME types with codecs:

type="video/ogg; codecs='theora, vorbis'"
type="video/mp4; codecs='avc1.42E01E'"
type="video/webm; codecs='vp8, vorbis'"

Even if we declare the MIME types with the proper codec in your HTML, there will be challenges related to the MIME types supported by the server where the server isn’t configured to support the MIME types your video, there will be playback issues.

source order

Consider the example of the below source elements. Ensure the source order which appears first support the latest version of browser.

<source src="example.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
<source src="example.webm" type='video/webm; codecs="vp8, vorbis"'>
<source src="example.ogv" type='video/ogg; codecs="theora, vorbis"'>
CodecDescription
MP4/H.264/AAC container/codecEnsure that the video will play on the iPad. It’s necessary to include the MP4/H.264 file first to ensure compatibility. It is recognized by IE9, Safari, and older versions of Chrome
theWebM/VP8/Vorbis container/codecSupported by later versions of Chrome that will eventually drop support for H.264. WebM video will also play in Firefox 4 and Opera 10.6
Ogg/Theora/Vorbis container/codecSupported by Firefox 3.5 and Opera 10.5. Although other browsers also support this combination, they’ll be using the other formats since they appear ahead of this one in the source order.
Creating Fallback Content

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

<video src="video.ogv" controls>
    Your device does not support HTML5 video. 
    <a href="video.ogg">Download the Learning to Love HTML5 introductory</a>
</video>

You could also include a download link for audio as a fallback content and also nest fallback content for lack of support for both the object and video elements.

<video src="video.ogv" controls>
    <object type="application/x-shockwave-flash" data="player.swf?file=" video.mp4 ">

<param name="movie " value="player.swf?file="video.mp4">
        <a href="video.mp4">Download the Learning to Love HTML5

introductory video</a>
    </object>
</video>
--

Setting Video Dimensions

We can customize the size of the video player by specifying the width and height of the video player:

Add the width and height attributes, and their corresponding values, to video.

<video controls width="640" height="360">
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogv" type="video/ogg" /> Your device does not support HTML5 video.
</video>
--

Html5 video is much like a img element in a html page. This means we can target the video element and its various components using JavaScript and we can even style the video element with CSS.

Lets create a custom control for video element. Our controls have three components:

  • ■ play/pause button
  • ■ timer that counts forward from zero
  • ■ mute/unmute button

The different parts of the video controls:

<div id="controls" class="hidden">
    <a id="playPause">Play/Pause</a>
    <span id="timer">00:00</span>
    <a id="muteUnmute">Mute/Unmute</a>
</div>
Media elements api
var videoEl = $('video')[0],
playPauseBtn = $('#playPause'),
vidControls = $('#controls'),
muteBtn = $('#muteUnmute'),
timeHolder = $('#timer');

videoEl.removeAttribute("controls");

The next step is to make our own custom controls visible. As mentioned earlier, we’ve used CSS to remove our controls from view by default. By using JavaScript to enable the visibility of the custom controls, we ensure that the user will never see two sets of controls.

videoEl.addEventListener('canplaythrough', function() {
    vidControls.removeClass("hidden");
}, false)
Playing and Pausing the Video
playPauseBtn.bind('click', function() {
    if (videoEl.paused) {
        videoEl.play();
    } else {
        videoEl.pause();
    }
});


videoEl.addEventListener('play', function() {
    playPauseBtn.addClass("playing");
}, false);
videoEl.addEventListener('pause', function() {
    playPauseBtn.removeClass("playing");
}, false);
Note
Disabling the Context Menu the video element’s context menu has an option for Save video as…. There’s been discussion online about how easy it is to save HTML5 video, and this could affect how copyrighted videos will be distributed.
Muting and Unmuting the Video’s Audio Track
muteBtn.bind('click', function() {
    if (videoEl.muted) {
        videoEl.muted = false;
    } else {
        videoEl.muted = true;
    }
});

videoEl.addEventListener('volumechange', function() {
    if (videoEl.muted) {
        muteBtn.addClass("muted");
    } else {
        muteBtn.removeClass("muted");
    }
}, false);
Responding When the Video Ends Playback
videoEl.addEventListener('ended', function() {
    videoEl.currentTime = 0;
    videoEl.pause();
}, false);
Updating the Time as the Video Plays
videoEl.addEventListener('timeupdate', function() {
    timeHolder[0].innerHTML = secondsToTime(videoEl.currentTime);
}, false);
--

Media Elements API

Events

Similar to the events canplaythrough, play, pause, volumechange, ended, and timeupdate events. Here are some of the other events available to you when working with HTML5 video and audio.

EventsDescription
canplayThis is similar to canplaythrough, but will fire as soon as the video is playable, even if it’s just a few frames. (This contrasts with canplaythrough, as you’ll remember, which only fires if the browser thinks it can play the video all the way to the end without rebuffering.)
errorThis event is sent when an error has occurred; there’s also an error attribute.
loadeddataThe first frame of the media has loaded.
loadedmetadataThis event is sent when the media’s metadata has finished loading. This would include dimensions, duration, and any text tracks (for captions).
playingThis indicates that the media has begun to play. The difference between playing and play is that play will not be sent if the video loops and begins playing again, whereas playing will.
seekingThis is sent when a seek operation begins. It might occur when a user starts to move the seek bar to choose a new part of the video or audio.
seekedThis event fires when a seek operation is completed.
Attributes

In addition to the attributes we’ve already seen, here’s a number of useful ones available to you.

AttributeDescription
playbackRateThe default playback rate is 1. This can be changed to speed up or slow down playback. This is naturally of practical use if you’re creating a fast-forward or rewind button, or a slow-motion or slow-rewind button.
srcAs its name implies, this attribute returns the URL that points to the video being played. This only works if you’re using the src attribute on the video element.
currentSrcThis will return the value of the URL pointing to the video file being played, whether it’s from the video element’s src attribute or one of the source elements.
readyStateThis attribute returns a numeric value from 0 to 4, with each state representing the readiness level of the media element. For example, a value of “1” indicates that the media’s metadata is available. A value of “4” is virtually the same as the condition for firing the canplaythrough event, meaning the video is ready to play, and won’t be interrupted by buffering or loading.
durationThis returns the length of the video in seconds.
bufferedThis represents the time ranges of the video that have buffered and are available for the browser to play.
videoWidth, videoHeightThese values return the intrinsic dimensions of the video, the actual width and height as the video was encoded—not what’s declared in the HTML or CSS. Those values can be accessed through the customary width and height attributes. You can also access attributes that are able to be declared directly in the HTML, such as preload, controls, autoplay, loop, and poster.
--

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.

MethodDescription
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
--

Manipulating Video With canvas

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

Explanation
1. Add video and canvas:

Add a button to trigger the drawing, as well as two canvas elements, one for a medium preview and one for a small.

snippet
<video id="origVideo" width="640" height="360">
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogv" type="video/ogg" /> Your device does not support HTML5 video.
</video>
<button title="Generate Preview" onclick="generatePreview();">Generate Preview</button>
<canvas id="previewMed"></canvas>
<canvas id="previewSm"></canvas>
2. Generate Preview:

create a function to generate the preview and set the JavaScript variables for our video and canvas elements:

snippet
<script>
function generatePreview() {
    var video = document.getElementById('origVideo');
    var canvas1 = document.getElementById('previewMed');
    var context1 = canvas1.getContext('2d');
    var canvas2 = document.getElementById('previewsSm');
    var context2 = canvas2.getContext('2d');

    Set Preview Dimensions:
        define the dimensions
    for each of the canvas drawings in the
    function:
    canvas1.width = 320;
    canvas1.height = 180;
    canvas2.width = 160;
    canvas2.height = 90;

    Add an Event Listener:
        add an event listener to trigger the canvas drawing upon video play:
        video.addEventListener('play', function() {
            drawVideo(this, context1, context2);
        }, false);

    close out the
    function:
    video.play();
}

//Draw Previews Lastly, add the function that draws each of the canvas previews:
function drawVideo(video, canvas1, canvas2) {
	if (video.paused || video.ended) return false;
	canvas1.drawImage(video, 0, 0, 320, 180);
	canvas2.drawImage(video, 0, 0, 160, 90);
	setTimeout(drawVideos, 25, video, canvas1, canvas2);
}
</script>
This function first checks to see if the video is playing.
if(video.paused || video.ended) return false;
If so, use drawImage with scaling to draw a canvas image that is half the size of the original video.
canvas1.drawImage(video,0,0,320,180);
And a second canvas that is half the size of previewMed:
canvas2.drawImage(video,0,0,160,90);
The scaling parameters in these examples are:
object.drawImage(source,x,y,width,height);
Where x and y represent the top left corner of the image on the target canvas, and width and height are the image's size on the target canvas. Finally, tell drawPreviews to call itself every 25 milliseconds, which roughly equals 40 frames per second (1000ms/40fps = 25):
setTimeout(drawVideos,25,video,canvas1,canvas2);
snippet
<video id="origVideo" width="640" height="360">
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogv" type="video/ogg" /> Your device does not support HTML5 video.
</video>
<button title="Generate Preview" onclick="generatePreview();">Generate Preview</button>
<canvas id="previewMed"></canvas>
<canvas id="previewSm"></canvas>
snippet
<script>
function generatePreview() {
    var video = document.getElementById('origVideo');
    var canvas1 = document.getElementById('previewMed');
    var context1 = canvas1.getContext('2d');
    var canvas2 = document.getElementById('previewsSm');
    var context2 = canvas2.getContext('2d');
    canvas1.width = 320;
    canvas1.height = 180;
    canvas2.width = 160;
    canvas2.height = 90;
    video.addEventListener('play', function() {
        drawVideo(this, context1, context2);
    }, false);
    video.play();
}

function drawVideo(video, canvas1, canvas2) {
    if (video.paused || video.ended) return false;
    canvas1.drawImage(video, 0, 0, 320, 180);
    canvas2.drawImage(video, 0, 0, 160, 90);
    setTimeout(drawVideos, 25, video, canvas1, canvas2);
}
</script>
<audio src="audio.ogg"></audio>
<canvas width="512" height="100"></canvas>
<button title="Generate Waveform" onclick="genWave();">Generate Waveform</button>
snippet
<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 +