Managing Media and More in HTML - Adding Links, Images, and Other Media - Beginning HTML5 & CSS3 For Dummies® (2013)

Beginning HTML5 & CSS3 For Dummies® (2013)

Part III

Adding Links, Images, and Other Media

10

Managing Media and More in HTML

In This Chapter

arrow Understanding media support in HTML5

arrow Working with audio, video, and more

arrow Crafting useful web page controls

arrow Working with frames in web pages . . . or not?

Increasingly, the web is becoming more than just a medium for accessing text and images. On the one hand, the web is embracing an ever-widening array of media, such as audio, video, and other forms of streaming media (video calls, video conferences, live audio, and so on). On the other hand, the web provides a platform for all kinds of interactive applications that provide services, crunch numbers, and do the kinds of things that people once called on computers to run locally and autonomously through their web browsers instead. Writing web-enabled software is beyond the scope of this book, but dealing with media in HTML5 is not.

remember_4c.epsHTML5 adds standard ways of playing media to the basic markup mix. Earlier versions of HTML had to rely on browser plug-ins to handle any kind of media. There was no guarantee that the right plug-in would be available for various specific kinds of media on your particular browser, even if plug-ins might be available for other browsers.

This chapter provides a quick tutorial on using various types of media in your web pages. You find out which media formats are web-friendly and how to use HTML5 elements to incorporate media into your web pages. You also discover how to use plug-ins for media, to support older browsers that may not accommodate the new media-handling capabilities in HTML5.


The long tail of web software

In statistics, the long tail refers to that portion of a distribution of numbers that follows the head or primary part of that kind of data. The head is where the bulk of the values concentrate, but there are also a lot of values distributed over a very long sequence at the tail end of the graph. In retail sales terminology, the long tail describes a strategy for selling a large number of unique or specialized items in fairly small quantities (the tail end of the distribution) in addition to a small number of popular items sold in very large quantities (the head of the distribution). This long tail adds to the overall market and increases sales overall.

For web browsers (and software in general), the long tail describes continued use of old software in smaller numbers over a long period of time, even after newer, more capable versions become available. That explains why, even though Internet Explorer is available in version 10 as we write this chapter, and Google Chrome is at version 27, some users are still running IE versions 6 or lower, and Chrome versions back in the teens. Web designers have to decide whether or not to support this long tail: If they do, they have to build pages that provide workarounds when they want to use newer features, such as the built-in HTML5 media handling capabilities, but don’t want to preclude users running older browsers from accessing such media, which requires running the right plug-in to play it back. Your call!


The Battle of the Media Formats

In getting HTML5 to the point where it could offer reasonable built-in media playback, there was quite a bit of discussion involved within the standards bodies’ working groups that defined this kind of markup. This is a sport that Texans sometimes call ’cussin’ and discussin’, where the ratio of the former to the latter varies directly with the heat of the debate. And, given that the debate got pretty hot in this arena from time to time, there were no doubt meetings where the various interests involved turned the air blue!

Here’s where things currently stand with media in HTML5. First, the current HTML5 specification recommends support for the royalty-free Ogg Vorbis (audio) and Ogg Theora (video) formats. But browser makers can choose to support whichever audio and video formats they like. Alas, this means that content authors (that’s you) cannot assume any particular format will work in all browsers. That’s a drag, as the upcoming Table 10-1 reveals.

The HTML Working Group (the folks who decide what goes into the HTML5 specification, also known as WHATWG at www.whatwg.org) believes it is desirable to specify at least one audio and video format for all browsers to support. What makes a media format ideal? An ideal format should do the following:

check Support good compression to keep file sizes and bandwidth consumption down

check Support good image or sound quality to deliver a positive media experience

check Impose low decode processor overhead to keep media from overwhelming the playback device

check Be royalty-free so browser makers and users don’t need to worry about licensing issues or potential patent infringements

check Include a hardware decoder for the format because mobile devices often can’t carry the processing load to decode media, especially video

Meet the major audio formats

A quick search of audio file formats shows that there are over 30 entries in this crowded field. For the purposes of this book, however, we focus on the major players supported in the most popular web browsers, as shown in Table 10-1 (which appears later in this chapter, in the“Comparing Traditional and HTML5 Media Handling” section). As is also the case with video, you can find both royalty-free and proprietary formats in our short list. The name inside the first set of parentheses after each format name identifies a common file extension associated with that format.

check Ogg Vorbis (Ogg; royalty-free): A lossy audio compression format distributed free of royalty or licensing fees with other open and free media projects. Vorbis is a music-oriented format, but Ogg also supports Opus (a human speech compression format) and the lossless FLAC compression format. Ogg is distributed under the open BSD license. Both FLAC and Vorbis are extremely popular music formats, with Vorbis preferred for the web because its compression, whereas lossy (which means some sound fidelity is sacrificed in the interests of saving on bandwidth) is well suited for streaming online delivery. The file extension, .ogg, comes from the name of the container in which Vorbis files are most commonly carried. (The same extension is also used for Theora video as noted in the next section.)

check MP3 (MP3; proprietary): This proprietary lossy audio compression format is one of the most widely used formats for audio files at present — it’s possibly even the most widely used format. MP3 stands for MPEG-2 Layer 3, which in turn identifies the efforts of the Motion Picture Experts Group to create a usable digital audio format that makes acceptable trade-offs between audio fidelity and file size. (An audio file created using a 128 kilobits per second streaming rate setting for MP3 produces a listenable file that is less than 10 percent of the size of its original CD audio counterpart.) MP3 files can be compressed at higher or lower bitrates to deliberately trade audio quality against file size (lower quality, smaller files) or file size against audio quality (higher quality, bigger files). The PC is a long-time supporter of MP3, which is very commonly used in Windows software of all kinds, including Internet Explorer for the web.

check Waveform Audio File Format, or WAVE (WAV; royalty-free): Usually known as WAV (thanks to its file extension), this audio format supports both compressed and uncompressed audio formats. WAV is a joint effort from IBM and Microsoft but requires no licensing or royalty payments. WAV works with numerous widely available audio codecs (encoders/decoders, which translate analog audio signals into digital patterns for storage, and digital patterns into analog audio signals for playback). The biggest issue with WAV is that its PC origin means it’s not as widely supported on Mac OS, Linux/Unix, or mobile device operating systems.

Each of these audio formats has its pros and cons, but Vorbis appears poised to become most widely supported. In fact, the Web Hypertext Application Technology Working Group (WHATWG) recommends that all browser makers include Ogg Vorbis and Theora support in future offerings.

Meet the major video formats

As with audio, many, many potential video formats are available for use on the web. But for the purposes of this book, we focus on the major players that are supported in the most popular web browsers included in Table 10-1 (which appears in the next section, “Comparing Traditional and HTML5 Media Handling”). As with audio, you can find both royalty-free and proprietary formats here, too. Here’s a list of the major players (the name inside the first set of parentheses after each format name identifies a common file extension associated with that format):

check Ogg Theora (Ogg; royalty-free): A free lossy video compression format distributed free of royalty or licensing fees with other open and free media projects. Ogg Theora is more or less the same in capability and bitrate efficiency as MPEG-4, or early versions of Windows Media Video (WMV), or RealVideo. Theora files make use of the Ogg container for delivery. (The same container also serves the Vorbis or FLAC audio formats.)

check H.264 (MP4; proprietary): More formally known as MPEG-4, H.264 or AVC (Advanced Video Coding) is a proprietary codec standard developed jointly by the ITU-T Video Coding Experts Group and the ISO/IEC JTC1 Motion Picture Experts Group (MPEG). This codec supports HD video and is widely used in

• Videos from Vimeo, YouTube, and the iTunes Store.

• Web software such as the Adobe Flash Player, Microsoft Silverlight.

• HDTV terrestrial, cable, and satellite feeds.

check VP8/9 (WebM; royalty-free): Free audio-video format designed for use with HTML5 video, a WebM file combines VP8 or VP9 video and Vorbis audio streams. It works natively with Firefox, Opera, and Chrome, and with plug-ins for Internet Explorer and Safari. The Google WebM hardware decoder is available to semiconductor companies at no cost, and it incurs no licensing or royalty fees.

Each of these video formats has its pros and cons, but Theora and WebM appear poised to become most widely supported, and WHATWG is recommending that all browser makers include Ogg Vorbis and Theora support in future offerings.

Comparing Traditional and HTML5 Media Handling

HTML5 supports a variety of media tags (and media formats) for media playback in web browsers. Because HTML5 remains something of a work in progress, not all formats work for all media in all browsers, as shown in Table 10-1. However, if you stick to the common denominators, you can find a way to deliver what you want to the biggest possible audience. And no matter what, given the WHATWG’s recommendations, the Ogg formats (Vorbis, Theora, and so forth) look like good bets.

technicalstuff_4c.epsTo read the discussions included in the HTML Living Standard document for audio and video elements in Section 4.8 “Embedded Content,” please visit this page:

www.whatwg.org/specs/web-apps/current-work/multipage/#auto-toc-4

Media Support in Modern Browsers

Sources: Developer.Mozilla.org “Using HTML5 audio and video”; MSDN Magazine “Working with Media in HTML5.”

* MI means “manual installation required.”

Mastering HTML5 Media Markup

Simply stated, there are two primary media elements for HTML5, both of which are absurdly easy to use. The audio element is named <audio>, and the video element is named <video>. In HTML5, the browser determines which players are built-in and thus available for use. You need to plan your use of audio and video accordingly, as you see in the sections on these two media elements that follow next, <audio> first, <video> second.

Making beautiful music with audio

Of course, there's more to the <audio> element than music — it happily plays back any kind of audio file, but we simply can't resist a good headline opportunity. Here's a simplified version of what audio markup looks like:

<audio src="sounds.ogg" controls>Alternatives</audio>

Here the src attribute points to the audio file you'd like to have played back. It specifies the location for the audio object for playback. The location must be a valid URI (Uniform Resource Identifier) that, just like a URL, identifies where the browser should look for the audio file.

The controls entry stands in for a number of control attributes you can use to manage audio playback and behavior, as follows (presented in alphabetical order):

check autoplay: Tells the browser to start playing audio as soon as the object file is loaded. The only legal value for this attribute is autoplay but no value is strictly required in HTML5.

check controls: Tells the browser to display an onscreen widget to control audio playback (usually with Pause/Play buttons, a progress bar, and volume controls). As with autoplay, the only legal value for this attribute is controls, but no value is strictly required in HTML5.

check loop: Tells the browser to go back to the beginning and keep playing when it gets to the end of the object file. Here, too, the only legal value for this attribute is loop, and no value is strictly required.

check preload: Tells the browser whether it should preload the object file, and if so how it should be preloaded. Possible values include

• none: Doesn't load any part of the audio file when the page loads

• metadata: Loads only the audio metadata when the page loads. It also sets up playback but doesn't have data loaded yet.

• auto: Loads entire audio file when the page loads

The preload attribute is ignored if autoplay is present.

The Alternatives section is very interesting and quite helpful in supporting older browsers. Page visitors see, or run, the content inside the <audio></audio> tags only if their browser doesn't support the audio element (because their browser ignores tags it doesn't recognize), but HTML5-savvy browsers are smart enough to skip such alternative directions. This is where you can call plug-ins for specific players and different file formats because you know that only visitors who can't use the built-in HTML5 audio playback capabilities will encounter this markup. We take advantage of this in the example that follows to show you how to call other file formats in case your chosen format can't be played. As shown, a browser that lacks HTML5 audio support would display the word Alternatives onscreen!

Here's some markup that won't play back an .ogg audio file until the user triggers the Play button on the onscreen controls, with continuous looping as long as the page stays onscreen. We also provide WAV and MP3 alternatives for older browsers:

<audio controls preload="none" loop>

<source src="sound.ogg" type="audio/ogg">

<source src="sound.wav" type="audio/x-wav">

<source src="sound.mp3" type="audio/mpeg">

<p>Browser does not support HTML5 audio; alternate playback provided.</p>

</audio>

tip_4c.epsBy default, if you don't include a src attribute in the opening <audio> tag, the target for the first <source> element is played in a browser that recognizes the HTML5 <audio> element. This setup makes it easy to stack up your playback options in the Alternatives section, starting with the one you want most, and so on. If players for the three formats are not available, no sounds will be played at all. As soon as the browser finds a player to match the type of sound file (.ogg first, .wav second, .mp3 third), the browser uses the player to play the sound, and then the browser continues processing the remainder of the HTML document that follows.

Figure 10-1 shows what this page inside a properly constructed HTML file with some additional text and information looks like onscreen in Chrome.

Moving media with video

Unlike audio, which doesn’t actually require much (or any) space on the screen, video requires an onscreen frame, as well as more sophisticated and more numerous controls. That’s why although the two markup elements are similar, video comes with considerably more baggage, even though the basic structure of the element remains the same as before:

<video src="video.ogg" controls>Alternatives</video>

9781118657201-fg1001.eps

Figure 10-1: An audio control bar displayed in Chrome.

Here the src attribute points to the video file you'd like to have played back. It specifies the name of the video object file for playback and must be a valid URI. Example: src="video.ogg".

The list of control attributes for video is considerably longer and a bit more complicated, too:

check autoplay: Tells the browser to start playing video as soon as the object file is loaded. Examples: autoplay or autoplay="autoplay".

check controls: Tells the browser to display an onscreen widget to control video playback (usually with Pause/Play buttons, a progress bar, and volume controls). Examples: controls or controls="controls".

check height: Sets the height, in pixels, of the box inside which the video will display. Example: height="480".

check loop: Tells the browser to go back to the beginning and keep playing when it gets to the end of the object file. Examples: loop or loop="loop".

check mediagroup: Used for synchronizing playback of multiple videos or media elements (such as a sign language track or an SAP track). Takes a string value, where all items with the same mediagroup value are treated together as members of that group. Example: mediagroup="movie".

check muted: Sets audio output state for playback; if present, audio is muted when playback begins. Use this when loud or startling audio might otherwise bother page visitors so that they can elect to turn on audio if they like. Examples: muted or muted="muted".

check poster: Specifies an image to display while the video file is not available (hasn't loaded yet). Example: poster="poster.jpg".

check preload: Tells the browser whether it should preload the object file, and if so how it should be preloaded. Possible values include:

• none: Does not load any part of the video file when the page loads

• metadata: Loads only the video metadata when the page loads. It also sets up playback but doesn't have data loaded yet.

• auto: Loads entire video file when the page loads

The preload attribute is ignored if autoplay is present.

check width: Sets the width, in pixels, of the box inside which the video displays. Example: width="640".

The following markup displays a video snippet from Wikipedia:

<video controls poster="poster.png"

src="http://upload.wikimedia.org/wikipedia/commons/5/5c/Cat.ogg"

width="640" height="480">

<source src="cat.webm" type="video/webm">

<source src="cat.mp4" type="video/mp4">

<p> Browser does not support HTML5 video; alternate playback provided.</p>

</video>

Figure 10-2 shows what this page inside a properly constructed HTML file with some additional text and information looks like onscreen in Chrome, just after the video concludes playback.”? The control bar for video is nearly identical to the control bar for audio. The difference is that the video control bar has a frame control at the far right. Please note also that alternatives for video playback work the same as they do for audio feedback, so you can stack your preferred player first for HTML5 browsers to use if they can, followed by other players in whatever order you prefer.

9781118657201-fg1002.eps

Figure 10-2: A video control bar displayed in Chrome.

Undergoing the conversion experience

So, what if you want to follow our lead and provide alternative file formats for your audio or video files? To make them available in the big three formats of each kind (.ogg, .wav, and .mp3 for audio; and .ogg, .mp4, and .webm for video), you need some conversion tools. Here are some good resources to help you get started down that path so that when you make files available, you can reach the broadest possible audience:

check About.com, “4 Free Audio Converter Software Programs”

http://pcsupport.about.com/od/fileextensions/tp/free-audio-converter.htm

check About.com, “5 Free Video Converter Programs and Online Services”

http://pcsupport.about.com/od/fileextensions/tp/free-video-converter.htm

tip_4c.epsThanks to these excellent articles, we’re pretty sure you can find something suitable for either category. If you don’t find what you need, you can do what we do when faced with such a dilemma: Simply search for “free audio converter” or “free video converter” and keep trying candidates until something sticks.


tip_4c.eps Mastering media in HTML5

After you start working with the audio and video elements (and the ever-helpful support source element, too), you’ll get a feel for making good use of audio and video in your web pages. But what we present here is just the tip of an enormous and incredibly interesting iceberg of information and activity. For more details on the various audio and video formats, search online for this generic phrase:

Play back format in HTML5

where you substitute your chosen format name (Ogg, Vorbis, Theora, MP4, MP3, WebM, or WAV,) for the format element therein. When we tried that approach in researching this chapter, we found oodles of great material readily available. You should, too!


Working with Web Page Controls

The controls attribute that HTML5 so helpfully provides for both the audio and video elements sets the stage for our next discussion where we present the various onscreen progress bars, gauges, and meters that HTML5 makes available for on-page use. The following sections look at the markup elements involved — meter, progress, and time — and include online examples at the tail end of each element. The section ends with a quick tutorial on how to update controls in real time on your web pages.

Displaying a meter bar

The HTML5 <meter> element lets you display a meter bar for various counters that you might manage over time to show readings for various metrics. The <meter> element includes these numerical attributes, whose values may be integers (that is, whole numbers) or decimal numbers:

check value: The current measured value for your meter

check high: States a value considered to be high for readings on this meter

check low: States a value considered to be low for readings on this meter

check max: Sets the upper bound for readings on this meter and its display

check min: Sets the lower bound for readings on this meter and its display

check optimum: States a value considered to be optimal for readings on this meter

Here’s a fully tricked-out markup example, shown in Figure 10-3 displayed in Chrome:

<meter high="90" low="10" max="100" min="0" optimum="50"

value="44">Center-seeking meter</meter>

Figure 10-3 shows the meter in the context of a complete HTML file, with some use of CSS to set off the meter display. The meter’s current value falls just below the optimal halfway mark.

9781118657201-fg1003

Figure 10-3: A simple centering meter.

tip_4c.epsThe high, low, and optimum attributes as well as the text enclosed between the opening <meter> and closing </meter> tags do not appear in the browser display of the meter. It's probably best to think of this information as a kind of built-in documentation to help explain how the meter works.

To see and play around with meter markup (and value settings), visit this page:

www.quackit.com/html_5/tags/html_meter_tag.cfm

For a nice demo of a meter at work (as you type into a text box, the character count goes up and the green meter bar gets longer), visit this page:

http://jsfiddle.net/RBUmQ/1/

The following is a snippet of HTML markup that shows three different meter bars: one for storage space consumption, one for voter turnout, and one for tickets sold. Don’t scratch your head too much about it: It’s just a contrived example.

<p>Storage space usage: <meter value="6" max="8">6 blocks used

(out of 8 total)</meter> </p>

<p>Voter turnout:

<meter value="0.75"><img alt="75%" src="graph75.png"></meter></p>

<p>Tickets sold: <meter min="0" max="100" value="75"></meter></p>

Tracking progress on activities

Whereas the meter element is designed to handle readings that can go up or down over time, the progress element is designed to report on activities that go one way only: up! Think of a typical progress bar that shows how far along you are on a software download, a file copy, or an install maneuver, and you've mastered the progress bar concept.

This simplicity makes the progress element something of a one-trick pony in the HTML5 world, and explains why it takes exactly two attributes:

check max: The value that represents completion of the task whose progress is being measured by this control

check value: The current value for the amount of progress achieved

Here’s an example of some progress markup:

<progress max="100" value="44">progress bar</progress>

Figure 10-4 shows a static snapshot of the bar displayed in Chrome. At runtime, green in the progress bar fills in from left to right (that is, start to end), showing that something is — or should be — happening.

9781118657201-fg1004

Figure 10-4: The progress element tracks completion of a task.

To fool around with progress bar markup online, visit this page:

www.quackit.com/html_5/tags/html_progress_tag.cfm

For a great demo (with access to underlying HTML5 markup and JavaScript for dynamic update of a progress bar), visit this page:

http://developerdrive.com/demo/progress_bar/demo.html

Here's a fun tutorial on what you can do with CSS and the progress element (see Parts IV and V of this book for many more details on working with CSS):

http://css-tricks.com/css3-progress-bars

Tracking and reporting on time

HTML5 adds a lot more data smarts to its repertoire, as compared with earlier HTML versions. Among these kinds of elements and their attributes, <time> permits content developers to use (and update) time values on their web pages in a variety of interesting ways.

The secret to <time> in HTML5 lies in understanding the kinds of values that this element's sole attribute — datetime — can take. This data type is called a date or time string and accommodates many forms for representing such information. The HTML5 specification explains how this works as follows:

The time element represents either a time on a 24 hour clock, or a precise date in the proleptic Gregorian calendar, optionally with a time and a time-zone offset.

This explanation could use some further explanation. Here’s a list of the formats time and date attributes embrace, including examples in case you prefer the “monkey-see, monkey-do” method of comprehension:

check Valid time HH:MM[:SS][.fff]: A 24-hour time where two-digit hours and minutes values are required, and seconds are optional, as are decimal fractions of a second. This means 8 a.m. is "08:00" but that 8 p.m. is "20:00".

check Valid date YYYY-MM-DD: A complete date where four-digit year, two-digit month, and two-digit day of month values are all required.

check Valid date and time with timezone offset: Combines the previous two value types — date first and time second with a T in the middle — and then adds a timezone offset to include timezone information. Thus 4 p.m. on September 11, 2001 Central (US) Time is "2001-09-11T16:00-06:00". Timezones range from -12:00 to +14:00, and you can use the capital letter Z (Zulu time) to denote +00:00 for Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT).

What does the "proleptic Georgian calendar" stuff mean? It means that for <time> element values, time begins at 0 AD (no BC dates, in other words). But because <time> is intended to provide time stamps and time values, this shouldn't be a problem for most content developers who will use this element to keep track of things like publication dates, most recent update dates, and so forth. The nice thing about time in HTML5 is that the content between the opening <time> and closing </time> tags is intended to be human-readable, and the value of the datetime attribute is intended to be machine-readable, so both humans reading web pages and computers handling them can read and use time information included in such pages.

Who knew that dealing with <time> could take so much time? The following example markup shows the preceding example formats in HTML5:

<time datetime="20:00">eight PM</time>

<time datetime="2001-09-11">another day of infamy (adoi)</time>

<time datetime="2001-09-11T16:00">4 PM adoi</time>

<time datetime="2001-09-11T16:00-06:00">4 PM adoi Central (US) time</time>

The result is shown in Figure 10-5. Note that only HTML cares about the datetime attribute value; humans see the corresponding text enclosed within the <time> element instead.

One important take-away from this set of examples should be the idea that careful labeling of the content inside the <time> element is important because it tells page visitors about time in their web browsers. But of course, if that's not why you're recording time, you needn't put any text inside the <time> element at all.

9781118657201-fg1005

Figure 10-5: Example time markup displayed in Chrome.

To fool around with <time> markup online, visit this page:

www.quackit.com/html_5/tags/html_time_tag.cfm

There's no real reason to update the datetime attribute in a <time> element, so we skip the pointers to JavaScript updating techniques in this section. That doesn't stop us from returning to that subject in the next section, though.

Updating HTML5 controls

We can share the secret to updating HTML5 controls in one word: JavaScript. Though it's not the only scripting tool available to web content developers (that's you!), it is probably the most popular and widely used of such tools. To make a progress bar show progress or a meter measure change over time, you need some way to update the value associated with the value attribute as the web page is processed. JavaScript offers lots of good ways to do this, including responding to events in the browser environment, polling changes to local variables, counting time (or other values), and so forth.

To really understand how to use the <progress> or <meter> elements in HTML5, you have to understand JavaScript (or another web-friendly scripting language). That's outside the scope of this particular book, though we did include examples you can imitate to take the "monkey-see, monkey-do" approach to putting this markup to work. If you want to do it right, however, you'll want to add to your reading list. In particular, you might find these other For Dummies books of great interest:

check HTML5 Programming with JavaScript For Dummies, by John Paul Mueller (April 2013), more or less picks up where we leave off here.

check PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies, by Steve Suehring and Janet Valade (April 2013), covers a full range of HTML5-related programming topics and tools. The book is designed as a comprehensive reference.