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.
--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
Value | Description |
---|---|
auto | auto indicates that the video and its associated metadata will start loading before the video is played. |
none | none indicates that the video shouldn’t load in the background before the user presses play. |
metadata | This 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"
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
AttributeThe 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
Attributeautoplay
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
attributeloop
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>
Extension | Description |
---|---|
.mp4 | The container format for the proprietary H.264 codec that encodes video for a full range of devices, including high definition. |
.ogv | The free, open source container format for the open source Theora codec. Results in lower quality than H.264. |
.webm | Another open source container format, which is used by the new, royalty-free VP8 codec from Google. |
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>
<source src="video.mp4" type="video/mp4" /> <source src="video.ogv" type="video/ogg" />
<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.
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"'>
Codec | Description |
---|---|
MP4/H.264/AAC container/codec | Ensure 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/codec | Supported 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/codec | Supported 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. |
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>
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:
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>
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)
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);
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);
videoEl.addEventListener('ended', function() { videoEl.currentTime = 0; videoEl.pause(); }, false);
videoEl.addEventListener('timeupdate', function() { timeHolder[0].innerHTML = secondsToTime(videoEl.currentTime); }, false);
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.
Events | Description |
---|---|
canplay | This 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.) |
error | This event is sent when an error has occurred; there’s also an error attribute. |
loadeddata | The first frame of the media has loaded. |
loadedmetadata | This event is sent when the media’s metadata has finished loading. This would include dimensions, duration, and any text tracks (for captions). |
playing | This 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. |
seeking | This 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. |
seeked | This event fires when a seek operation is completed. |
In addition to the attributes we’ve already seen, here’s a number of useful ones available to you.
Attribute | Description |
---|---|
playbackRate | The 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. |
src | As 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. |
currentSrc | This 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. |
readyState | This 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. |
duration | This returns the length of the video in seconds. |
buffered | This represents the time ranges of the video that have buffered and are available for the browser to play. |
videoWidth , videoHeight | These 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. |
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.
Method | Description |
---|---|
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 |
We can create a visualization of your HTML5 video using canvas.
Add a button to trigger the drawing, as well as two canvas elements, one for a medium preview and one for a small.
<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>
create a function to generate the preview and set the JavaScript variables for our video and canvas elements:
<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>
if(video.paused || video.ended) return false;
canvas1.drawImage(video,0,0,320,180);
canvas2.drawImage(video,0,0,160,90);
object.drawImage(source,x,y,width,height);
setTimeout(drawVideos,25,video,canvas1,canvas2);
<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>
<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>
<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>