ad

ad

Bidvertiser Ad

q ad 2

Friday, 2 May 2014

HTML Videos

Videos can be embedded in HTML pages with several methods.

Playing Videos in HTML

Example

<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  <source src="movie.webm" type="video/webm">
  <object data="movie.mp4" width="320" height="240">
    <embed src="movie.swf" width="320" height="240">
  </object>
</video>

Try it yourself »


Problems, Problems, and Solutions

Playing videos in HTML is not easy!
You must add a lot of tricks to make sure your video will play in all browsers (Internet Explorer, Chrome, Firefox, Safari, Opera) and on all hardware (PC, Mac , iPad, iPhone).
In this chapter W3Schools summarizes the problems and the solutions.

HTML Video - Using <embed>

The <embed> tag defines a container for external (non-HTML) content.
The following HTML fragment displays a Flash video embedded in a web page:

Example

<embed src="intro.swf" height="200" width="200">

Try it yourself »
Problems
  • If the browser does not support Flash, the video will not play
  • iPad and iPhone do not support Flash videos

HTML Video - Using <object>

The <object> tag tag can also define a container for external (non-HTML) content.
The following HTML fragment displays a Flash video embedded in a web page:

Example

<object data="intro.swf" height="200" width="200"></object>

Try it yourself »
Problems:
  • If the browser does not support Flash, the video will not play
  • iPad and iPhone do not support Flash videos

The HTML5 <video> Element

The HTML5 <video> tag defines a video or movie.
The <video> element works in all modern browsers.
The following example uses the HTML5 <video> tag, which specifies one MP4 file (for Internet Explorer, Chrome, Firefox 21+, and Safari), and one OGG file (for older Firefox and Opera). If something fails, it will display a text:

Example

<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

Try it yourself »
Problems:
  • You must convert your videos to many different formats
  • The <video> element does not work in older browsers

HTML Video - The Best Solution

The best solution is to use the HTML5 <video> element + the <embed> element.
The example below uses the <video> element and tries to play the video either as MP4 or OGG. If that fails, the code "falls back" to try the <embed> element:

HTML 5 + <object> + <embed>

<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  <object data="movie.mp4" width="320" height="240">
    <embed src="movie.swf" width="320" height="240">
  </object>
</video>

Try it yourself »
Problems:
  • You must convert your videos to many different formats

HTML Video - YouTube Solution

However, maybe the easiest way to display videos in HTML pages, is to use YouTube (see next chapter)!

HTML Video - Using A Hyperlink

If a web page includes a hyperlink to a media file, most browsers will use a "helper application" to play the file.
The following code fragment displays a link to a Flash video. If a user clicks on the link, the browser will launch a helper application to play the file:

Example

<a href="intro.swf">Play a video file</a>

Try it yourself »


Tips About Inline Videos

When a video is included in a web page it is called inline video.
If you plan to use inline videos, be aware that many people find it annoying. Also note that some users might have turned off the inline video option in their browser.
Our best advice is to include inline videos only in pages where the user expects to see a video. An example of this is a page which opens after the user has clicked on a link to see the video.

HTML Multimedia Tags

= Tag added in HTML5.
Tag Description
<embed> Defines an embedded object
<object> Defines an embedded object
<param> Defines a parameter for an object
<audio> Defines sound content
<video> Defines a video or movie
<source> Defines multiple media resources for media elements (<video> and <audio>)
<track> Defines text tracks for media elements (<video> and <audio>)

HTML Sounds / Audio

Sounds can be embedded in HTML pages with several methods.

Problems, Problems, and Solutions

Playing audio in HTML is not easy!
You must know a lot of tricks to make sure your audio files will play in all browsers (Internet Explorer, Chrome, Firefox, Safari, Opera) and on all hardware (PC, Mac , iPad, iPhone).
In this chapter W3Schools summarizes the problems and the solutions.

Using Plug-ins

A plug-in is a small computer program that extends the standard functionality of the browser.
Plug-ins can be added to HTML pages using the <object> tag or the <embed> tag. 
These tags define containers for resources (normally non-HTML resources), which, depending on the type, will either be displayed by the browsers, or by an external plug-in.

HTML Audio - Using <embed>

The <embed> tag defines a container for external (non-HTML) content.
The following code fragment should play an MP3 file embedded in a web page:

Example

<embed height="50" width="100" src="horse.mp3">

Try it yourself »

Problems:

  • Different browsers support different audio formats
  • If a browser does not support the file format, the audio will not play without a plug-in
  • If the plug-in is not installed on the users' computer, the audio will not play

HTML Audio - Using <object>

The <object> tag can also define a container for external (non-HTML) content.
The following code fragment should play an MP3 file embedded in a web page:

Example

<object height="50" width="100" data="horse.mp3"></object>

Try it yourself »

Problems:

  • Different browsers support different audio formats
  • If a browser does not support the file format, the audio will not play without a plug-in
  • If the plug-in is not installed on the users' computer, the audio will not play

The HTML5 <audio> Element

The HTML5 <audio> tag defines sound, such as music or other audio streams.
The <audio> element works in all modern browsers.
The following example uses the HTML5 <audio> tag, which specifies one MP3 file (for Internet Explorer, Chrome, Firefox 21+, and Safari), and one OGG file (for older Firefox and Opera). If something fails, it will display a text:

Example

<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  <source src="horse.ogg" type="audio/ogg">
  Your browser does not support this audio format.
</audio>

Try it yourself »

Problems:

  • You must convert the audio files into different formats
  • The <audio> element does not work in older browsers

HTML Audio - The Best Solution

The best solution is to use the HTML5 <audio> element + the <embed> element.
The example below uses the <audio> element and tries to play the audio either as MP3 or OGG. If that fails, the code "falls back" to try the <embed> element:

Example

<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  <source src="horse.ogg" type="audio/ogg">
  <embed height="50" width="100" src="horse.mp3">
</audio>

Try it yourself »

Problems:

  • You must convert the audio files into different formats
  • The <embed> element cannot "fall-back" to display an error message

HTML Audio - Using A Hyperlink

If a web page includes a hyperlink to a media file, most browsers will use a "helper application" to play the file.
The following code fragment displays a link to an MP3 file. If a user clicks on the link, the browser will launch a helper application to play the file:

Example

<a href="horse.mp3">Play the sound</a>

Try it yourself »


Tips About Inline Sounds

When sound is included in a web page, or as part of a web page, it is called inline sound.
If you plan to use inline sounds, be aware that many people will find it annoying. Also note that some users might have turned off the inline sound option in their browser.
Our best advice is to include inline sounds only in pages where the user expects to hear sounds. An example of this is a page which opens after the user has clicked on a link to hear a recording.

HTML Multimedia Tags

= Tag added in HTML5.
Tag Description
<embed> Defines an embedded object
<object> Defines an embedded object
<param> Defines a parameter for an object
<audio> Defines sound content
<video> Defines a video or movie
<source> Defines multiple media resources for media elements (<video> and <audio>)
<track> Defines text tracks for media elements (<video> and <audio>)

HTML - Plug-ins

The purpose of a plug-in, is to extend the functionality of the HTML browser.

HTML Helpers (Plug-ins)

A helper application is a small computer program that extends the standard functionality of the browser. Helper applications are also called plug-ins.
Examples of well-known plug-ins are Java applets and Adobe Flash Player.
Plug-ins can be added to web pages with the <object> tag or the <embed> tag. 
Plug-ins can be used for many purposes: to display maps, scan for viruses, verify your bank id, and much more. The restrictions are few.

What is The Best Way to Play Audio or Video in HTML?

The best way to embed audio in a web page is to use the HTML5 <audio> element.
The best way to embed video in a web page is to use the HTML5 <video> element.

The <object> Element

The <object> element is supported in all major browsers.
The <object> element defines an embedded object within an HTML document.
It is used to to embed plug-ins (like Java applets, ActiveX, PDF, and Flash) in web pages.
It can also be used to embed another webpage, or web content like images, into HTML documents.
Note The text between <object> and </object> is displayed if the browser doesn't support the tag.

The HTML <param> tag is used to pass parameters to the plug in.

Example

<object width="400" height="50" data="bookmark.swf"></object>

Try it yourself »


The <embed> Element

The <embed> element is supported in all major browsers.
The <embed> element defines a container for an external application or interactive content (a plug-in).
Many web browsers have supported the <embed> element for a long time. However, it has not been a part of the HTML specification before HTML5.
The <embed> element will validate in an HTML5 page, but not in an HTML 4 page.

Example

<embed width="400" height="50" src="bookmark.swf">

Try it yourself »

Note Note that the <embed> element does not have a closing tag. It can not contain alternative text.

HTML Multimedia

Multimedia on the web is sound, music, videos, movies, and animations.

What is Multimedia?

Multimedia comes in many different formats. It can be almost anything you can hear or see.
Examples: Pictures, music, sound, videos, records, films, animations, and more.
Modern web pages often have embedded multimedia elements, and modern browsers have support for various multimedia formats.
In this tutorial you will learn about the different multimedia formats.

Internet Browser Support

The first Internet browsers had support for text only, and even the text support was limited to a single font in a single color. Then came browsers with support for colors, fonts and text styles, and support for pictures was also added.
The support for sounds, animations, and videos is handled in different ways by various browsers. Some multimedia elements is supported, and some requires an extra helper program (a plug-in) to work.
You will learn more about plug-ins in the next chapters.

Multimedia Formats

Multimedia elements (like sounds or videos) are stored in media files.
The most common way to discover the type of a file, is to look at the file extension. When a browser sees the file extension .htm or .html, it will treat the file as an HTML file. The .xml extension indicates an XML file, and the .css extension indicates a style sheet file. Pictures are recognized by extensions like .gif, .png and .jpg.
Multimedia files also have their own formats and different extensions like: .swf, .wav, .mp3, .mp4, .mpg, .wmv, and .avi.

Video Formats

Videoformats          MP4 is the new and upcoming format for internet video.

MP4 is recommended by YouTube.

MP4 is supported by Flash players and HTML5.

Format File Description
AVI .avi AVI (Audio Video Interleave) was developed by Microsoft, and is therefore playable on all Windows computers. It is commonly used in video cameras and TV hardware, but is difficult to play on non-Windows computers.
WMV .wmv WMV (Windows Media Video) was developed by Microsoft, and is therefore playable on all Windows computers. It is commonly used in video cameras and by TV hardware, but is difficult to play on non-Windows computers.
QuickTime .mov QuickTime was developed by Apple, and is therefore playable on all Apple computers. It is commonly used in video cameras and by TV hardware, but is difficult to play on non-Apple computers.
RealVideo .rm
.ram
RealVideo was developed by Real Media to allow video streaming with low bandwidths. It is still used for online video and Internet TV, but because of the low bandwidth priority, the quality is also low.
Flash .swf
.flv
Flash was developed by Macromedia. Flash requires an extra component to play in a browser.
Ogg .ogg Theora Ogg was developed by the Xiph.Org Foundation.
WebM .webm WebM is a project (www.webmproject.org) by the web giants, Mozilla, Opera, Adobe, and Google.
MPEG .mpg
.mpeg
MPEG, developed by the Moving Pictures Expert Group, used to be the most popular video format on the Internet. It used to be supported by all major browsers, but it is not supported by HTML5.
MPEG-4
or MP4
.mp4 MP4 is the upcoming format on the internet. It is supported by all major browsers in HTML5. YouTube recommends using MP4, and it is commonly used in newer video cameras and TV hardware.

Note Only MP4, WebM, and Ogg video is supported by the newest HTML5 standard.


Sound Formats

MP3 is the newest format for compressed recorded music. The term MP3 has become synonymous with digital music.
If your website is about recorded music, MP3 is the choice.
Format File Description
MIDI .mid
.midi
MIDI (Musical Instrument Digital Interface) is a format for electronic music devices like synthesizers and PC sound cards. MIDI files do not contain sound, but digital musical instructions (notes) that can be played by electronics (like your PC's sound card). Click here to play The Beatles.
Since MIDI files only contains instructions; they are extremely small. The example above is only 23K in size, but it plays for nearly 5 minutes. MIDI is supported by many software systems/platforms. Because it is the main format for binary music, it is supported by most software, including Internet browsers.
RealAudio .rm
.ram
RealAudio was developed Real Media to allow streaming of audio (online music, Internet radio) with low bandwidths.
WMA .wma WMA (Windows Media Audio), compares in quality to MP3, and is compatible with most music players, except the iPod. WMA files can be delivered as a continuous flow of data, which makes it practical for use in Internet radio or on-line music.
AAC .aac AAC (Advanced Audio Coding) was developed by Apple as the default format for iTunes.
WAV .wav WAVE (more known as WAV) was developed by IBM and Microsoft. WAV is compatible with Windows, Macintosh, and Linux operating systems.
Ogg .ogg  Ogg was developed by the Xiph.Org Foundation.
MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3 is the most popular format for music players. The encoding system combines good compression (small files) with high quality. It is supported by all major browsers.
MP4 .mp4 MP4 is a video format, but it can also be used with audio only. MP4 video is the upcoming video format on the internet. This can lead to an automatic support for MP4 audio by all major browsers.

Note Only MP3, WAV, and Ogg audio is supported by the newest HTML5 standard.

HTML5 Server-Sent Events

HTML5 Server-Sent Events allow a web page to get updates from a server.

Server-Sent Events - One Way Messaging

A server-sent event is when a web page automatically gets updates from a server.
This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.
Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
Server-Sent Events are supported in all major browsers, except Internet Explorer.

Receive Server-Sent Event Notifications

The EventSource object is used to receive server-sent event notifications:

Example

var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
  document.getElementById("result").innerHTML + =event.data + "<br>";
  };

Try it yourself »
Example explained:
  • Create a new EventSource object, and specify the URL of the page sending the updates (in this example "demo_sse.php")
  • Each time an update is received, the onmessage event occurs
  • When an onmessage event occurs, put the received data into the element with id="result"

Check Server-Sent Events Support

In the tryit example above there were some extra lines of code to check browser support for server-sent events:
if(typeof(EventSource) !== "undefined")
  {
  // Yes! Server-sent events support!
  // Some code.....
  }
else
  {
  // Sorry! No server-sent events support..
  }


Server-Side Code Example

For the example above to work, you need a server capable of sending data updates (like PHP or ASP).
The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams.
Code in PHP (demo_sse.php):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
Code in ASP (VB) (demo_sse.asp):
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: " & now())
Response.Flush()
%>
Code explained:
  • Set the "Content-Type" header to "text/event-stream"
  • Specify that the page should not cache
  • Output the data to send (Always start with "data: ")
  • Flush the output data back to the web page

The EventSource Object

In the examples above we used the onmessage event to get messages. But other events are also available:
Events Description
onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occurs

HTML5 Web Workers

A web worker is a JavaScript running in the background, without affecting the performance of the page.

What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
Internet Explorer 10, Firefox, Chrome, Safari and Opera support Web workers.

HTML5 Web Workers Example

The example below creates a simple web worker that count numbers in the background:

Example

Count numbers:


Try it yourself »


Check Web Worker Support

Before creating a web worker, check whether the user's browser supports it:
if(typeof(Worker) !== "undefined")
  {
  // Yes! Web worker support!
  // Some code.....
  }
else
  {
  // Sorry! No Web Worker support..
  }


Create a Web Worker File

Now, let's create our web worker in an external JavaScript.
Here, we create a script that counts. The script is stored in the "demo_workers.js" file:
var i = 0;

function timedCount()
{
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}

timedCount();
The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.
Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.

Create a Web Worker Object

Now that we have the web worker file, we need to call it from an HTML page.
The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in "demo_workers.js":
if(typeof(w) == "undefined")
  {
  w = new Worker("demo_workers.js");
  }
Then we can send and receive messages from the web worker.
Add an "onmessage" event listener to the web worker.
w.onmessage = function(event){
  document.getElementById("result").innerHTML = event.data;
  };
When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.

Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.
To terminate a web worker, and free browser/computer resources, use the terminate() method:
w.terminate();


Full Web Worker Example Code

We have already seen the Worker code in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<br><br>

<script>
var w;

function startWorker()
{
if(typeof(Worker) !== "undefined")
{
  if(typeof(w) == "undefined")
    {
    w = new Worker("demo_workers.js");
    }
  w.onmessage = function (event){
    document.getElementById("result").innerHTML = event.data;
  };
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
}
}

function stopWorker()
{
w.terminate();
}
</script>

</body>
</html>

Try it yourself »


Web Workers and the DOM

Since web workers are in external files, they do not have access to the following JavaScript objects:
  • The window object
  • The document object
  • The parent object

HTML5 Application Cache

With HTML5 it is easy to make an offline version of a web application, by creating a cache manifest file.

What is Application Cache?

HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.
Application cache gives an application three advantages:
  1. Offline browsing - users can use the application when they're offline
  2. Speed - cached resources load faster
  3. Reduced server load - the browser will only download updated/changed resources from the server

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
Internet Explorer 10, Firefox, Chrome, Safari and Opera support Application cache.

HTML5 Cache Manifest Example

The example below shows an HTML document with a cache manifest (for offline browsing):

Example

<!DOCTYPE HTML>
<html manifest="demo.appcache">

<body>
The content of the document......
</body>

</html>

Try it yourself »


Cache Manifest Basics

To enable application cache, include the manifest attribute in the document's <html> tag:
<!DOCTYPE HTML>
<html manifest="demo.appcache">
...
</html>
Every page with the manifest attribute specified will be cached when the user visits it. If the manifest attribute is not specified, the page will not be cached (unless the page is specified directly in the manifest file).
The recommended file extension for manifest files is: ".appcache"
Note A manifest file needs to be served with the correct MIME-type, which is "text/cache-manifest". Must be configured on the web server.


The Manifest File

The manifest file is a simple text file, which tells the browser what to cache (and what to never cache).
The manifest file has three sections:
  • CACHE MANIFEST - Files listed under this header will be cached after they are downloaded for the first time
  • NETWORK - Files listed under this header require a connection to the server, and will never be cached
  • FALLBACK - Files listed under this header specifies fallback pages if a page is inaccessible

CACHE MANIFEST

The first line, CACHE MANIFEST, is required:
CACHE MANIFEST
/theme.css
/logo.gif
/main.js
The manifest file above lists three resources: a CSS file, a GIF image, and a JavaScript file. When the manifest file is loaded, the browser will download the three files from the root directory of the web site. Then, whenever the user is not connected to the internet, the resources will still be available.

NETWORK

The NETWORK section below specifies that the file "login.asp" should never be cached, and will not be available offline:
NETWORK:
login.asp
An asterisk can be used to indicate that all other resources/files require an internet connection:
NETWORK:
*

FALLBACK

The FALLBACK section below specifies that "offline.html" will be served in place of all files in the /html/ catalog, in case an internet connection cannot be established:
FALLBACK:
/html/ /offline.html
Note: The first URI is the resource, the second is the fallback.

Updating the Cache

Once an application is cached, it remains cached until one of the following happens:
  • The user clears the browser's cache
  • The manifest file is modified (see tip below)
  • The application cache is programmatically updated

Example - Complete Cache Manifest File

CACHE MANIFEST
# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js

NETWORK:
login.asp

FALLBACK:
/html/ /offline.html

Note Tip: Lines starting with a "#" are comment lines, but can also serve another purpose. An application's cache is only updated when its manifest file changes. If you edit an image or change a JavaScript function, those changes will not be re-cached. Updating the date and version in a comment line is one way to make the browser re-cache your files.


Notes on Application Cache

Be careful with what you cache.
Once a file is cached, the browser will continue to show the cached version, even if you change the file on the server. To ensure the browser updates the cache, you need to change the manifest file.
Note: Browsers may have different size limits for cached data (some browsers have a 5MB limit per site).