Audio and Video - Interactivity and Multimedia - Creating a Website: The Missing Manual (2015)

Creating a Website: The Missing Manual (2015)

Part 4. Interactivity and Multimedia

Chapter 16. Audio and Video

In the early days of the Internet, websites were about as jazzy as an IRS form. You’d see pages filled with an assortment of plain text, links, and more plain text. Over time, the Web matured, and web pages started to change as designers embraced the joys of color, pictures, and tacky clip art. But when that excitement started to wear off, it was time for a new trick—multimedia.

Multimedia is a catch-all term for a variety of technologies and file types, which have different computer requirements and pose different web design challenges. Multimedia includes everything from the irritating jingle that plays in the background of your best friend’s home page to the wildly popular video clip of a cat playing the piano. (Depressing fact: That cat has over 40 million views, and you’re unlikely to ever create a web page that’s half as popular.)

In this chapter, you’ll learn how to put audio players and video playback windows into your web pages. You’ll also learn to overcome the limitations of old browsers by using a Flash fallback system, which ensures that pretty much any web-connected computer can listen to your music and watch your videos. And finally, once you’ve learned how to do all this on your own, you’ll see how to simplify your life by hosting your video files on YouTube.

Understanding Multimedia

There comes a point when all new web designers want more than mere text and pictures on their pages. Even spruced-up fonts and elegant page layouts don’t satisfy the design envy many newcomers feel when they spot a site loaded with sound and motion. That’s understandable: You, too, want to trick out your pages with audio and video. But before you can jazz up your site, you need to understand a few basics of multimedia.

Linking and Embedding

One of the key choices you make when you outfit your pages with multimedia is whether to link to or embed the files.

Linking to multimedia content is the simplest but least glamorous approach. The link points to an audio or video file stored along with all your other website files. There’s really nothing to creating linked multimedia. You use the same lowly anchor element and href attribute you used inChapter 6. Here’s an example:

Would you like to hear <a href="IndustrialNoiseBand.mp3">Industrial Noise</a>?

Figure 16-1 shows what happens when you click one of these babies.

When you click a link to a multimedia file, your browser decides what to do. If you’re using an older browser, or if your browser doesn’t recognize the file format, it asks if you want to save the file or open it in another program (top). But if your browser recognizes the file format, it opens a blank page with playback controls and starts playing the audio (bottom)

Figure 16-1. When you click a link to a multimedia file, your browser decides what to do. If you’re using an older browser, or if your browser doesn’t recognize the file format, it asks if you want to save the file or open it in another program (top). But if your browser recognizes the file format, it opens a blank page with playback controls and starts playing the audio (bottom).

NOTE

It makes absolutely no difference what kind of software your web host’s server runs. When someone clicks a link to an audio file, the browser downloads the file to the visitor’s computer and plays it there, not from the server.

Embedding multimedia is a more advanced approach. It integrates music or video into your HTML page. As a result, you can create rich combinations of text, sound, and video.

NOTE

The distinction between linking and embedding multimedia is the same as the distinction between linking to a picture (with the <a> element), and embedding it right in your page (with the <img> element).

You use the <audio> element to embed an audio player on your page and the <video> element to show a video on your page. These two newer elements didn’t exist until HTML5. Before that, web developers had to fiddle around with the clunky <embed> element, which was notoriously finicky and never managed to work for every visitor.

Today, browsers understand both the <audio> and <video> elements. Even mobile browsers work with them. In fact, there’s just one browser still kicking around that doesn’t know what to do with <audio> and <video> elements, and that’s Internet Explorer 8, which commands around 3 percent of the worldwide browser market at the time of this writing. If this worries you, don’t panic—you can create audio- and video-enhanced pages that have a Flash-powered fallback player for ancient browsers. You’ll learn how to add one on Adding a Flash Fallback.

Hosted Multimedia

One way to avoid all these browser headaches is to use hosted multimedia—audio and video files stored on someone else’s server but displayed on your web page. The best-known example of hosted multimedia is YouTube, a ridiculously popular site that plays back hundreds of millions of video clips every day.

Hosted multimedia is an excellent choice if you want to include really large files, particularly movie clips, on your page. It won’t tap out your website’s bandwidth (Assessing Your Needs). Best of all, you don’t need to worry about making sure your media files work with different browsers and operating systems, because the media hosting service does all that work. The only drawback is that you give up a fair bit of control. For example, if you host your videos on YouTube, you need to abide by its rules, which restrict you from posting videos with nudity, dangerous acts, violence, or copyrighted material. (And even if you think your video is using copyrighted material fairly—for example, in the context of a larger work of commentary, criticism, or satire—the copyright holder can probably persuade YouTube to yank it down unless you pay a small army of lawyers to argue otherwise.)

Despite these conditions, YouTube is still far and away the most practical way to share clips. You’ll learn to use YouTube on Uploading Videos to YouTube.

Playing Audio Files

The first ingredient you need to create a music-playing page is an audio file. Your best bet is one encoded using the popular MP3 standard. That way, you can rest assured that your page will work on the latest version of every browser in existence.

TIP

For best results, take an audio track in an uncompressed format (like WAV) and use it to generate an MP3 audio file. Most basic audio editors can perform this task. Audacity (http://audacity.sourceforge.net) is a free editor for Mac and Windows that fits the bill, although you’ll need to install the LAME MP3 encoder to get MP3 support (http://lame1.buanzo.com.ar). Goldwave (www.goldwave.com) is a similarly capable audio editor that’s free to try but sold for a nominal fee.

Here’s an example of a page that uses the <audio> element in the simplest way possible:

<!DOCTYPE html>

<html>

<head>

<title>A Taste of Scarlatti</title>

</head>

<body>

<h1>Relax, Music</h1>

<p>I've picked some music for you. Press the play button to listen to

Scarlatti's K. 184 sonata.</p>

<audio src="scarlatti.mp3" controls></audio>

</body>

</html>

The src attribute identifies the audio file you want to play. In this example, a browser looks for that file in the same folder as the page. Of course, you could also put your music file in a subfolder on your server and then use a relative path in the markup (Relative URLs).

NOTE

It goes without saying that you shouldn’t put an audio file on your website unless you created it, the content creator has given you permission, or you can verify that it’s in the public domain. Plenty of websites provide royalty-free music you can use on your pages, so long as you give credit to the composer somewhere on your site. For some good examples of free music catalogs, visit http://incompetech.com/music or www.bensound.com or http://musopen.org/music.

The controls attribute tells a browser to display a basic set of playback controls. Each browser has a slightly different version of these controls, but they always serve the same purpose—to let your guest start and stop playback, jump to a new position in the file, and change the volume (Figure 16-2). To try out this example, find it on the companion site (http://prosetech.com/web), which has both the HTML page and the corresponding MP3 file.

NOTE

The <audio> and <video> elements must have both a start and an end tag. You can’t use empty element syntax, like <audio />.

Although the playback controls look slightly different depending on the browser, they function the same way. This figure shows the audio player in Chrome. It provides buttons for playing and pausing the audio, as well as muting the sound and adjusting the volume

Figure 16-2. Although the playback controls look slightly different depending on the browser, they function the same way. This figure shows the audio player in Chrome. It provides buttons for playing and pausing the audio, as well as muting the sound and adjusting the volume.

Along with the basic src and controls attributes, the <audio> element offers several other options, which you’ll read about below.

Automatic Playback

Most people like to browse the Web in peaceful silence. That means no trance-hypno-ambient background tracks, no strange disco beats, and no sudden cymbal crashes. This aversion to noise may be due to the fact that something like 98 percent of all web browsing takes place on company time.

But if you like to startle and annoy people, or if you’re absolutely convinced that your audience really does want some funky beats, you can bring on the background music by adding the autoplay attribute, which tells a browser to start playback as soon as it finishes loading the page. It looks like this:

<p>The music now blaring from your speakers is

Scarlatti's K.184 sonata.</p>

<audio src="scarlatti.mp3" controls autoplay></audio>

<p>I hope you didn't tell your colleagues you were working!</p>

Without autoplay, it’s up to the person viewing the page to click the Play button, which is obviously a politer way of handling things.

If you’re really determined to annoy your visitors, you can use the <audio> element to play background music mercilessly by adding the autoplay attribute and removing the controls attribute. This creates an automatic music player that guests can’t shut off. The only reason to take this step is if you create your own controls, using JavaScript. For example, you might create a JavaScript-powered button that switches off the audio, or you might use the <audio> element to play music and sound effects for a JavaScript game embedded in the page.

NOTE

Creating your own music players and controlling the <audio> and <video> elements with JavaScript are two tasks beyond the scope of this book. You can learn more from the book HTML5: The Missing Manual (O’Reilly), which demonstrates how to create custom players, or you can dive in headfirst with a custom-player-building tutorial from the Web. (There are many, but you can find one popular article at http://tinyurl.com/custom-player.)

Preloading Media Files

One useful HTML5 attribute for multimedia files is preload, which tells a browser when to download a file. Set preload to auto, and the browser starts downloading the whole media file once it opens the page, so the file’s available as soon as a guest clicks Play. Of course, the download takes place in the background, so your visitor can scroll around and read the page without waiting for the download to finish.

The preload attribute works with two other values, too. Use metadata to tell the browser to grab the first small chunk of data from the file, which is enough to determine some basic details, like the total length of the audio. Or you can use none, which tells the browser to hold off on the download. You might use one of these options to save bandwidth, for example, if you have a page stuffed full of <audio> elements and you don’t expect the visitor to play more than a few of them.

<audio src="scarlatti.mp3" controls preload="metadata"></audio>

When you use the metadata or none values, the browser downloads the audio file as soon as someone clicks Play. Happily, browsers can play one chunk of audio while downloading the next without a hiccup unless you’re working over a slow network connection.

If you don’t set the preload attribute, browsers can do what they want, and different browsers make different assumptions. Most browsers assume auto as the value, but Firefox uses metadata. Furthermore, it’s important to note that the preload attribute isn’t a rigid rule, but a recommendation you give the browser—one that it might ignore, depending on other factors. (And some slightly older versions of browsers don’t pay attention to the preload attribute at all.)

NOTE

If you have a page stuffed with <audio> elements, the browser creates a separate strip of playback controls for each one. Your visitor can listen to one audio file at a time or play them all at once.

Looping Playback

Finally, the loop attribute tells a browser to start over at the beginning when playback ends. You can use this technique to keep your visitors happy with endlessly looping background music:

<audio src="scarlatti.mp3" controls loop></audio>

In most browsers, playback is fluid enough that you can use this technique to create a seamless, looping soundtrack. The trick is to choose a loopable piece of audio that ends where it begins.

Although many websites sell audio loops, you can download one for free at Flash Kit (www.flashkit.com/loops). Flash Kit offers a large and excellent catalog of nearly 10,000 loops ranging in style from ambient to urban. They were originally designed for Flash players, but you can also download them in MP3 format, which is what the <audio> element requires.

NOTE

Loops are the audio equivalent of a wallpaper tile. They’re short snippets of music specially designed so that the beginning picks up where the end leaves off. You can play an audio loop over and over again, and the result is a seamless background track. In a first-rate loop, the repetition isn’t immediately obvious, and you can happily listen to it for several minutes.

Showing Video Clips

Now that you’ve conquered the challenges of audio and learned to put music into your web pages, you’re ready to move on to the challenge of video content.

To show video content, you use the <video> element, which works for video files much like the <audio> element works for audio files. Here’s an example that plays an MP4 video file:

<!DOCTYPE html>

<html>

<head>

<title>Embarrassing Party Video</title>

</head>

<body>

<h1>It's Less Fun (When the Police Come)</h1>

<p>Party was going great until the fine fellows at 24th division

came by on a noise complaint.</p>

<video src="arrest.mp4" controls></video>

<p>Click the play button to see what happened to us.</p>

</body>

</html>

Once again, the controls attribute adds a handy set of playback controls to your page (Figure 16-3). In most browsers, these controls disappear when you click somewhere else on the page and return when you point to the movie link.

To build this simple page on your own, download the arrest.mp4 file from the companion site (http://prosetech.com/web). Create a new web page in the same folder, and add the <video> element inside.

Every browser has a slightly different style for the video window, but the playback buttons are all virtually the same. Chrome’s video player offers the same buttons as its audio player, plus one—a button in the bottom-right corner that expands the video to fill the entire screen

Figure 16-3. Every browser has a slightly different style for the video window, but the playback buttons are all virtually the same. Chrome’s video player offers the same buttons as its audio player, plus one—a button in the bottom-right corner that expands the video to fill the entire screen.

NOTE

If you right-click a video window that uses the <video> element, you’ll get a simple menu that includes the option to save the video file on your computer. Depending on the browser, it may also include commands for changing the playback speed, looping the video, taking it full screen, and muting the sound.

Video formats aren’t quite as simple as audio formats. That’s because you need to consider two details: the codec, which is a sort of recipe that compresses your video, and the container, which is the package that holds the encoded video and audio. In the video world, there’s a dizzying range of codec-and-container combinations. To ensure that your video plays back on the widest range of browsers, your video file should meet two criteria:

§ You should encode it with the popular H.264 codec. These days, H.264 is the recording format of choice for most consumer devices, from smartphones to video cameras.

§ You should store it in an MP4 (also known as MPEG-4) container. You can usually tell that you have the right type of container by looking at the file extension, which should be .mp4.

Follow these rules, and your video will play on the modern version of every browser.

NOTE

Even if you have the right type of file (an MP4 file that holds H.264-encoded content), it’s probably too big to be practical for your website. Preparing Video for the Web explains a bit more about how to convert and slim down video files.

NOSTALGIA CORNER: THE FORMAT WARS

Browser makers spent several years battling it out over different multimedia formats. The war over video formats was particularly nasty, and it still hasn’t completely subsided. At the moment, every browser supports H.264 (sometimes reluctantly). However, there’s no way to know if format disagreements might erupt again. For example, Google, the creator of Chrome, has officially pledged to remove H.264 support in favor of the free WebM codec in a future browser release (although it now seems unlikely that that will actually happen).

If the format wars do erupt again, the <audio> and <video> elements are ready. That’s because they both support a format fallback system. Here’s how it works: Instead of supplying a single source file in a single format with the src attribute, you offer up a list of files by adding a <source> element for each one. For example, if you have a web video in two different formats, you add two <source> elements inside the <video> element, one for each file. When a browser processes your page, it scans through this list until it finds a video in a format that it supports.

This multiple-file system is messy and awkward. It also wastes your time and your web space, because it’s up to you to encode each media file in multiple formats. To learn more, check out the reference for the <source> element in Appendix B (<small> (Small Print)). Or read a detailed tutorial of the format fallback system at http://tinyurl.com/vid-for-ev.

Configuring the Video Window

The <video> element has the same src, controls, preload, autoplay, and loop attributes as the <audio> element. However, if you choose automatic playback, you can make it slightly less obnoxious by throwing in the muted attribute, which shuts off the sound on most browsers. Your guest can switch the audio back on by clicking the speaker icon, as usual.

The <video> element also adds three more attributes: height, width, and poster.

The width and height attributes set the size of the playback window (in pixels). Here’s an example that creates a playback window that measures 400 x 300 pixels:

<video src="arrest.mp4" controls width="400" height="300"></video>

If you decide to supply the width and height attributes, make sure they match the true dimensions of the video. Technically, you don’t need to add these details, because a browser can figure out what size to make the video box when it loads the video file. However, there’s an advantage to making these details explicit. That’s because it forces the browser to reserve the right amount of space for the playback window right off the bat, preserving your carefully crafted layout as the video loads (or even if the video fails to load altogether).

NOTE

No matter what dimensions you use to size the video box, the video frame always keeps its proper proportions. For example, if you take a 400 x 300-pixel video and put it in an 800 x 450-pixel video box, you’ll get the biggest video frame that fits in the box without stretching, which is 600 x 450 pixels. This leaves 100 pixels on each side of the video frame, which browsers leave as blank space.

Finally, the poster attribute lets you supply an image that browsers display in place of the video in three situations: if the browser hasn’t downloaded the first frame of the video yet, if it couldn’t find the selected video file, or if you set the preload attribute to none.

<video src="arrest.mp4" controls poster="police_cuffs.jpg"></video>

Preparing Video for the Web

Audio and video files exhibit some hefty differences. Most importantly, video files are big. Even the smallest of them is many times the size of an audio recording of a full-length Mahler symphony.

Handling this much data without trying your visitors’ patience is a true test. In the following sections, you’ll learn how to prepare your video for the Web and let your visitors view it.

Hosting your own video files is a task meant for ambitious multimedia mavens. The key stumbling block is the sheer size of digital video. On a digital camcorder, every second of video can chew through 1 to 3 MB of storage (depending on the recording quality and format you use). Put together a 5-minute clip, and you’re looking at a staggering 300 to 900 MB file. Not only is this awkward to manage, but it’s also enough to take a bite out of any webmaster’s server and bandwidth allocations.

What can you do to make a web video both look good and perform well? You can always use someone else’s web-ready video (or pay a video-editing company lots of money to trim yours down to web proportions). Assuming that’s not what you want, you have two choices:

§ Record at lower quality. Many video cameras let you record using lower-quality settings for the sole purpose of putting video on the Web. This way, you can dodge conversion headaches and send video straight to your site.

§ Lower the quality afterward. More commonly, you need to go through a long process of re-encoding your high-quality video to convert it to a size suitable for the Web. To do this, you need a video-editing or video-conversion program (see the box on Encoding Your Media for tips on choosing one). It may take a bit of time to get this approach working, because you need to pick a program, settle on the right settings, and check your results. But once you iron out the kinks, this is the best solution, because it gives you the flexibility to retain as much quality as you can in your web video. It’s a particularly handy strategy if you plan to use a hosting service like YouTube. YouTube does best with high-quality video, because it does its own re-encoding when you upload your video files.

UP TO SPEED: ENCODING YOUR MEDIA

Plenty of programs can edit and convert video files. Some are free, while others are professional tools with prices to match. However, there are good choices out there for even casual video creators. If you need to edit your video (for example, snip out pieces, add fades and transitions, or superimpose captions over the action), you should consider a video editing tool. Two basic choices are Windows Movie Maker, included with Windows, and iMovie for the Mac. If you use Windows Movie Maker, however, you’ll need one of the free conversion programs described below to convert the final Windows Media Video file (.wmv) into a legitimate MP4 file (.mp4).

If you already have the video you want and simply need a way to convert it to MP4 format or compress it to a web-friendly size, two free, open-source conversion tools can help: HandBrake (available at http://handbrake.fr, and shown in Figure 16-4) and Miro Video Converter (www.mirovideoconverter.com). Both programs offer Windows and Mac versions and can convert a wide range of formats. Miro is slightly simpler to use, while HandBrake lets you tweak a few more advanced options for the encoding.

Here’s how to get your video ready for the Web:

1. Film your movie.

Take a couple of lessons from video aficionados and film your video in a way that makes it easier to compress and introduces less distortion: Keep camera movements smooth and gradual, and don’t film complex patterns. Your compressed video will look better.

If you’re using a smartphone or a tablet, remember to always film in landscape orientation (so the long edge of the device is horizontal). In other words, you want the picture to be short and wide, like a computer monitor or a television screen. If you ignore this advice and film in portrait mode, you’ll be disappointed when you play your video in a web page. That’s because the video player will shrink down your tall, skinny video and pad the sides with oceans of black space.

2. Connect your device to your computer using a USB cable.

Other modes of transport are possible, but usually less practical. For example, if you have a video on a smartphone, you can upload it to a web storage service or email the video file to yourself. But because video files are so big, these approaches are often slow and awkward.

3. Copy your video file from your device to your computer.

You may have a program that automatically copies pictures and movie files to your computer. Examples include a photo and media management program like Adobe Lightroom, Picasa, or iPhoto (if you’re moving videos from an iPhone to a Mac).

If you plug in your device and no program offers to perform the import, you may need to transfer the files on your own. Fortunately, it’s a relatively simple job. Just browse the folders on your device until you find a video file (look for big files with extensions like .mp4 or .mov). Then drag one or more files to a folder on your computer so you can work with them.

4. Use a video-editing program to snip out just the video segment you want.

Some programs let you add music or special effects at this point, too. There’s no shortage of options here, from simple, budget-friendly editors like iMovie and Windows Movie Maker to professional packages like Adobe Premiere Elements and Apple’s Final Cut Pro.

5. Re-encode that piece of video in a highly compressed format.

If all the format information in your program sounds like gobbledy-gook, look for an option that clearly says “web video” when you save your clip. (If you’re still looking for a program that can perform this sort of conversion, check out the box on Encoding Your Media.)

Technically, you make three choices in this step:

o Video format. As discussed earlier, the best choice is to create an MP4 file encoded using the H.264 codec.

o Video dimensions. If your source video already has the dimensions you want, you don’t need to change anything. But if you want to show a smaller video window in your web page, you might decide to scale down your video to match, because this reduces its file size. These days, videos are usually recorded in a widescreen aspect ratio, and they commonly fall into one of these pixel dimensions: 640 x 360 (usually the smallest you’ll want to go), 854 x 480, 1280 x 720 (known as 720p, or High Definition), and 1920 x 1080 (known as 1080p, or Full High Definition).

o Video quality. As with JPEG pictures, the greater the compression, the more detail you lose. Some video conversion tools let you pick a quality setting (Figure 16-4). Others let you choose the bitrate (the number of bits set aside to store each second of video). The smaller the bitrate, the lower the quality and the smaller the final video file.

Re-encoding video is time-consuming—even a speedy computer can take several times as long as the length of the original clip. The good news is that at the end of the process, you’ll have a more manageable web-ready file—say, a 20 MB file for a full 3-minute clip.

NOTE

If you plan to create a website with a lot of digital audio and video, you need to reconsider your site’s storage and bandwidth requirements (see Choosing Your Host). Unlike ordinary HTML pages and web graphics, multimedia files can grow quite large, threatening to overwhelm your space and bandwidth allotment. You can avoid this problem by using a hosted multimedia service like YouTube, in which case the video views cost you neither web space nor bandwidth.

Although HandBrake is full of settings, you need to consider changing only a few of them. Pull the Quality slider to the left to create a video file that’s smaller and of lower quality

Figure 16-4. Although HandBrake is full of settings, you need to consider changing only a few of them. Pull the Quality slider to the left to create a video file that’s smaller and of lower quality.

Fallbacks for Old Browsers

The <audio> and <video> elements are great tools when they work, which is most of the time. But if your page runs into an old browser that doesn’t recognize HTML5 attributes, things aren’t quite so smooth.

Usually, the only browser you need to worry about is Internet Explorer (specifically, IE 8 and older). Even though IE 8 is more than six years old, it’s still kicking around on ancient Windows XP computers that can’t run newer versions of the browser. IE 8 doesn’t know anything about HTML5. If it sees the <audio> and <video> elements, it ignores them and displays the rest of your page with no playback controls or video window.

To deal with this situation, you need to include fallback content nestled inside the <audio> or <video> element. That way, if a browser doesn’t understand the element, it displays alternate content. For example, instead of showing a video player window, your page can show a link to download the video:

<video src="arrest.mp4" controls>

Click here to download the <a href="arrest.mpg">arrest.mpg</a> video.

</video>

Browsers that don’t understand HTML5 (like IE 8) will act as though they saw this:

Click here to download the <a href="arrest.mpg">arrest.mpg</a> video.

Of course, a link isn’t nearly as good as a real video window. To compensate, you can use another type of playback window if the <video> element fails. There are two reliable ways to do that without HTML5:

§ Use a YouTube video window. The drawback is that you’ll need to upload your video to YouTube, as described on Adding a Flash Fallback.

§ Use a Flash video player. The world has plenty of Flash players, and many of them are free for noncommercial use. And best of all, most support H.264, which means you don’t need to go to the work of re-encoding your files.

Either way, you need to take a bunch of markup and paste it inside the <video> element, so that the Flash plug-in becomes the fallback for browsers that don’t understand HTML5. You can see the HTML for a YouTube player on Showing a YouTube Video in a Web Page. You’ll find the markup for a Flash player in the next section.

UP TO SPEED: THE ROLE OF FLASH

Flash is a versatile plug-in that’s slowly being replaced by HTML5. Just a few years ago, Flash was a top tool for programmers who wanted to create rich, interactive websites and games. Today, a mixture of HTML5 and JavaScript is more likely to fill that role, but Flash lives on as a way to play video without relying on HTML.

Visitors can’t use Flash unless they have a Flash plug-in installed. That said, good estimates suggest that an overwhelming 99 percent of web-connected desktop computers already have the plug-in. The real strength of Flash is that even very old computers are likely to have the Flash plug-in.

It might occur to you that you could add a Flash player to your page and leave out HTML5 altogether. After all, doesn’t virtually every computer have Flash? The problem is that Flash doesn’t play well with mobile devices. In particular, Flash doesn’t work at all on iPhones and iPads for reasons that are partly technical and partly political. In other words, if you want people to see your videos on Apple’s current crop of mobile devices, you need to start with HTML5 and use Flash as a last resort for browsers that don’t do HTML5.

Adding a Flash Fallback

If you’re interested in a Flash video player, your first step is to pick the one you want to use. Two popular choices are JW Player (http://www.jwplayer.com) and Flowplayer Flash (http://flash.flowplayer.org). With either one, you need to sign up at the website and then pick a plan. You’re interested in the free plan, which gets you the Flash player only. (You can pay money for them to host your videos and to get extra features in the Flash player.)

For example, the process of using JW Player goes like this:

1. Visit www.jwplayer.com.

2. Click the Order Now button.

A detailed page appears with different pricing plans. Ignore the option of paying for hosting (which gets JW Player to host your video files on its site, instead of keeping it on your own site).

3. Under the Free option, click Get It Now.

4. Provide your email address, and then click Get Started.

JW Player sends you a confirmation email, with a link you need to click.

5. Confirm your account by clicking the link in your email.

Once you click the link, the JW Player site asks you to create a password.

6. Choose a password to complete your account registration.

Now you go to JW Player’s Publish Wizard page.

7. Click “Publish a Video Now” to get the ball rolling.

JW Player needs three pieces of information to create your Flash player (Figure 16-5).

8. Fill in the information for your video.

o Media File is the crucial detail. Identify the MP4 video file that you want to show in your video window. Just type in its name, as you do with the <video> element. The JW Player can then play your video as long as it’s in the same folder as your page. If you want to get fancy, you can use a relative path, like videos/arrest.mp4 to point to a video in a subfolder on your website.

o Poster Image is an optional image that appears in the video window before playback starts. It plays the same role as the poster attribute in the <video> element.

o Media Title is an optional descriptive name for your video. It appears in the middle of the video window, before playback starts. It’s also used if you create a playlist with this video.

NOTE

You don’t need to upload the media file or poster image. You just need to tell JW Player what their filenames are. That way, the JW Player site can create the right markup to show the player on your page.

In this example, you’re about to create the markup for a JW Player-powered video window. The player will show the arrest.mp4 video that’s on your site

Figure 16-5. In this example, you’re about to create the markup for a JW Player-powered video window. The player will show the arrest.mp4 video that’s on your site.

9. Click Publish Now.

The next step asks you to configure your player (Figure 16-6).

10.Choose the size of your video window. Optionally, you can specify any of the other settings on this page.

Usually, you’ll pick Responsive, which means the player sizes itself to match your video file. Your other choice is Fixed Dimensions, in which case you need to set the exact height and width of the window in pixels.

You can also choose a skin for your player, which sets the color scheme and the styling for the video box border and its controls. But because you’ve opted to use the free version of JW Player, you’re limited to the standard black-and-gray skin.

In the Playback Options section, you can make a few more minor adjustments. For example, you can check the Autostart setting to start playback as soon as the browser loads the page, and Repeat to make the video loop continuously. Make sure you set the Primary State option toFlash, not HTML5. That’s because you want to use JW Player as a fallback only, not an all-purpose player.

11.Click Get Embed Code.

Now you’re rewarded with the markup and JavaScript code you need to put your customized version of the JW Player on your site.

When you create the JW Player markup, you pick a few options to style the video box, and the website spits out the code you need

Figure 16-6. When you create the JW Player markup, you pick a few options to style the video box, and the website spits out the code you need.

12.Copy the first <script> element and put it in the <head> section of your web page.

The first <script> element points to a block of JavaScript code stored on the JW Player website. Your page uses this code to create the player. Here’s an example:

<script src="http://jwpsrv.com/library/VgIvAs0OEeSUiw4AfQhyIQ.js"></script>

Part of this URL looks like a string of gibberish letters. In truth, it’s a unique code that identifies you to the JW Player site.

13.Copy the rest of the markup, and then put it inside the <video> element in your web page.

Once you add the <script> element, you can put the playback window wherever you want in your page using a second block of HTML markup that the JW Player site provides. It consists of an empty <div> container and a <script> element with a bit more JavaScript code:

<div id='playernCvWpRtuIEqB'></div>

<script type='text/javascript'>

jwplayer('playernCvWpRtuIEqB').setup({

file: 'arrest.mp4',

image: '//www.longtailvideo.com/content/images/jw-player/lWMJeVvV-876.jpg',

title: 'Party arrest',

width: '100%',

aspectratio: '16:9',

primary: 'flash'

});

</script>

The code in the <script> element creates the playback window according to the options you specified and places it in the <div> container. But you don’t see the messy JavaScript and Flash details that make everything happen, because the JW Player site stores them.

Remember, the JW Player is a fallback. You don’t want to use it unless the <video> element fails. That means you need to put the JW Player inside your <video> element. Here’s a complete page that puts the pieces together:

<!DOCTYPE html>

<html>

<head>

<title>Embarrassing Party Video</title>

<script src="http://jwpsrv.com/library/VgIvAs0OEeSUiw4AfQhyIQ.js"></script>

</head>

<body>

<h1>It's Less Fun (When the Police Come)</h1>

<p>Party was going great until the fine fellows at 24th division

came by on a noise complaint. </p>

<video src="arrest.mp4" controls>

<div id='playernCvWpRtuIEqB'></div>

<script type='text/javascript'>

jwplayer('playernCvWpRtuIEqB').setup({

file: 'arrest.mp4',

image: '//www.longtailvideo.com/content/images/jw-player/

lWMJeVvV-876.jpg',

title: 'Party arrest',

width: '100%',

aspectratio: '16:9',

primary: 'flash'

});

</script>

</video>

<p>Click the play button to see what happened to us.</p>

</body>

</html>

To see how the JW Player works, find an old browser that doesn’t understand HTML5, or cheat by removing the <video> element from your page, so that it contains the JW Player script and nothing else. That way, you’ll see the same content as ancient, HTML5-ignorant browsers.

NOTE

With Flash’s standard security settings, you can’t play a movie from your hard drive. That means that if you create a test page with JW Player and you try to run it from your computer, it won’t work. You need to upload the page to a web server (along with your video file), and then try it out.

Uploading Videos to YouTube

Before YouTube hit the scene, video clips hadn’t really taken off on the Web. They were all-around inconvenient: slow to download, with often jerky and sporadic playback. Today, the landscape has shifted. Web connections are faster and every browser supports video playback through HTML5 or Flash. Ordinary people own all sorts of digital video gadgets that can shoot short movies, from true video cameras to digital cameras, smartphones, and webcams. Popular clips rocket around the world, going from unknown to Internet sensation in a matter of hours. Family members, adventurers, and wannabe political commentators all regularly use video to keep in touch, show their skills, and dish the dirt.

YouTube (www.youtube.com) is at the forefront of this revolution. It currently ranks as the world’s third most-popular site (behind Google and Facebook), and it’s held that spot for years. And YouTube’s range of content is staggering. With a quick search, you can turn up both amateur and professional content, including funny home videos, product reviews and announcements, homemade music videos, clips from movies and television shows, and ordinary people spouting off on just about any topic.

If you’re still considering options for putting your video online, there are three great reasons to use YouTube:

§ It’s easy. When you use YouTube, you don’t need to worry about converting your video to the right format, re-encoding it to make it smaller, or adding a Flash fallback. YouTube handles all these concerns gracefully, using HTML5 or Flash, depending on what your visitor’s browser understands. It even encodes your video into several different resolutions, so that people on slow connections get a smaller video file that won’t choke up halfway through, while people on fast connections can enjoy your video in high quality.

§ It extends the reach of your website. YouTube is one of the most popular sites on the Web. If you’re lucky, a YouTube video can increase your audience from a few people to millions of eager clip-watchers. By putting your movies on YouTube, you increase the odds that someone will discover it and possibly visit your site afterward. For example, many of the most popular clip-makers capitalize on their YouTube popularity by selling themed merchandise on their sites. Others use AdSense (Google AdSense), which includes special ad boxes that sit unobtrusively at the bottom of the playback window.

§ The bandwidth is free. If you put a video on your site, you need to worry about the space it takes up and whether you have enough bandwidth to satisfy every visitor. This is a particular problem if your video goes viral (becomes briefly and instantly popular). If you have a basic shared hosting account, this attention can crash your site.

In the following sections, you’ll see how to upload your first YouTube video and how to embed it in one of your pages.

Preparing a Video for YouTube

Before you upload a video, it helps to understand how YouTube works and the sort of files it expects. Here are some essential bits of YouTube wisdom:

§ YouTube accepts video in virtually any format, including MPEG2, MPEG4, MOV, DivX, WMV, WebM, AVI, and FLV. That means you probably won’t need to convert your file before submitting it.

§ YouTube automatically re-encodes the videos you upload so that web visitors can watch them without teeth-gnashing delays. For this reason, YouTube recommends that you upload the original version of your clip. In other words, don’t re-encode your video. Doing so only wastes your time and lowers the movie’s quality because YouTube re-encodes the clip anyway to prepare it for playback.

NOTE

Depending on the length of your clip and the video format you used, your original file could be gargantuan (easily running into hundreds of megabytes). Even though YouTube allows uploads of files up to 128 GB, videos of this size aren’t practical for everyone (they take forever to upload, for one thing). If you have a slow web connection, or if your Internet service provider limits how much data you can transfer in a month, you might need to ignore YouTube’s recommendation and shrink your video files before you upload them. If so, use one of the tools described on Preparing Video for the Web.

§ YouTube plays back both standard and widescreen video. For best results, use the largest dimensions your recording device allows. When you upload your file, YouTube creates different copies of it at different sizes. That way, viewers get a video optimized for their playback window, whether that’s a standard desktop-browser window, a full-screen window, or a tiny window on a mobile device.

§ Read the YouTube Help section. From time to time, YouTube changes its recommendations or accepts new formats. To get the lowdown before you upload, visit http://tinyurl.com/66onkub.

Uploading a Video

Once your video’s ready, it’s time to put it online. The process is refreshingly straightforward:

1. Go to www.youtube.com. Click the Sign In link in the top-right corner of the page. Then log in with your Google account.

Anyone can browse and view YouTube videos (you can choose from over a billion clips at the time of this writing). But to upload your own movies, you need a Google account. If you’ve somehow made it to this point in the book without creating one, you need one now. Supply the usual particulars, including your email address, password, location, and date of birth, and then sign yourself up.

2. Click the Upload button at the top of the page.

You’ll see an upload “drop box” (Figure 16-7).

To get started with YouTube, you need to drop a video file in the big white box (or click the big arrow in the middle)

Figure 16-7. To get started with YouTube, you need to drop a video file in the big white box (or click the big arrow in the middle).

3. Drag and drop a file into the upload box, or click “Select file to upload” to browse for it on your hard drive.

Either way, you can upload more than one video at a time.

As soon as you pick your clips, YouTube begins uploading them (Figure 16-8). With the time-consuming upload process under way, you can add information about your video at your leisure.

As YouTube uploads a file, it estimates how long the transfer will take. While you wait, you can fill out the descriptive information for your video

Figure 16-8. As YouTube uploads a file, it estimates how long the transfer will take. While you wait, you can fill out the descriptive information for your video.

4. Fill in the details about your video.

You need to supply a title and description, which YouTube displays on your video page and in its search results. You also need to specify a category for your video and add one or more tags. When other people search YouTube using keywords that match your category or tags, there’s a better chance that your video will turn up in the search results.

NOTE

Don’t worry if the information you enter isn’t perfect. You can change it anytime. Just find your video in the My Videos section, select it, and then click Edit.

5. Choose a privacy setting (Public, Unlisted, or Private).

o Public. A public video turns up in YouTube search results, and anyone can watch it.

o Unlisted. Anyone can also watch an unlisted video, but people will need the right URL to find it—the video won’t turn up in an ordinary search.

o Private. If you mark a clip as private, only YouTubers you explicitly identify can see it, and only after they log into YouTube.

6. Optionally, click Advanced Settings to configure a few more settings.

Here are some options you might find useful:

o Use the “Allow comments” and “Users can view ratings for this video” settings to let people respond to your video. For example, you can ban people from commenting (turn off “Allow comments”), or allow only comments you approve (turn “Allow comments” on and then choose “Approved” instead of “All”). Ordinarily, YouTube allows all comments, giving the site a raucous community atmosphere. In some cases, it makes sense to limit comments and ratings (for example, if you cover a sensitive topic and you’re worried about attracting abusive comments). But the vast majority of videos on YouTube allow comments and are heavily commented. Videos that don’t let people opine are likely to be ignored.

o Choose a category to classify your video and help make sure it turns up in the right searches. YouTube has categories like Comedy, Education, Gaming, and News.

o Use the “Recording date” and “Video location” settings to identify when and where you recorded your video.

o Use the “Allow embedding” setting to control whether other people can embed your video on their web pages. But take note: If you don’t allow this, it not only stops other people from showcasing your video; it also prevents you from embedding your own video on your website.

7. Wait.

YouTube says it typically takes 1 to 5 minutes to upload each megabyte of video if you have a high-speed connection, so this is a good time to get a second cup of coffee.

While you’re waiting, you can drag another video file onto the upload page and start uploading it as well. Or, if you’ve given up completely, click the tiny X icon next to the progress bar to stop the upload.

Once YouTube uploads and converts your video, it replaces the progress bar with a “Processing Done” message.

If you get really tired of waiting, consider skipping ahead to step 9. That’s right, you can tell YouTube to publish your video even before it finishes uploading the file. YouTube then schedules your movie for publication, which means it will become live on the site as soon as YouTube finishes processing it.

8. Pick a thumbnail for your video from the Video Thumbnails section.

The video thumbnail is a single frame from your movie that appears in the YouTube video window before playback starts. It also shows up when YouTube lists your film in a search result.

As YouTube processes your video, it takes a frame grab every few seconds and adds it as a possible thumbnail.

9. Click Publish.

Now your video is completely configured and live before the entire web world (Figure 16-9).

Once you publish your video, YouTube gives you a link to it

Figure 16-9. Once you publish your video, YouTube gives you a link to it.

TIP

If you want to edit the information for an already-uploaded video, remove the video, or get some fascinating statistics about the people who’ve seen it, you need to use the YouTube video manager. Scroll down to the bottom of the upload page and click the Video Manager button in the bottom-right corner. (Or, if you’re somewhere else on YouTube, click the Account button in the top-right corner, click Creator Studio, and then choose Video Manager from the menu of links on the left.

Showing a YouTube Video in a Web Page

Once your video is ready, you can watch it in several ways:

§ You can search for it on YouTube.

§ You can put a link on your web page that leads to your YouTube video page. Just visit that page and copy the URL from the address bar.

§ You can play it back in a YouTube window on one of your web pages. This is the most powerful approach. It lets you combine the look and feel of a self-hosted video with YouTube’s high performance and solid browser support.

Embedding videos is as easy as copying a snippet of HTML into your page. Here’s what you do:

1. Go to the YouTube page for your video.

You can use the URL you got when you published your video (Figure 16-9). If you’ve already moved on, you can browse through the videos in your account. Click the Account button at the top right of any YouTube page, choose Creator Studio, and then click your recently uploaded video.

2. Click the Share button underneath the video window.

It sits between your video’s title and description. When you click it, YouTube shows a small panel of sharing information.

3. Click Embed.

This gives you the HTML markup you need (Figure 16-10), instead of a mere link.

Here’s the markup you need to display this video on your web page. The code’s crammed into a single line

Figure 16-10. Here’s the markup you need to display this video on your web page. The code’s crammed into a single line.

4. Right-click the box with the HTML markup and choose Copy.

5. Edit your HTML page and paste in the YouTube markup.

Put the markup where you want the video window to appear (Figure 16-11).

Embedding lets you watch your video in a page of your own devising

Figure 16-11. Embedding lets you watch your video in a page of your own devising.

Here’s the complete markup that creates the page in Figure 16-11:

<!DOCTYPE html>

<html>

<head>

<title>Embarrassing Party Video</title>

</head>

<body>

<h1>It's Less Fun (When the Police Come)</h1>

<p>The following video window is brought to you by the fine people

at YouTube.</p>

<iframe width="560" height="315" src=https://www.youtube.com/embed/

iDEHv7QS0fA?rel=0

frameborder="0" allowfullscreen></iframe>

<p>Click it to start playing.</p>

</body>

</html>

To embed your video, YouTube uses the <iframe> element (<iframe> (Inline Frame)) to stake out a small rectangular section of your page and insert some content there. To place the playback window in a specific spot, put the <iframe> element inside a <div> element, and then use style rules to position the <div>.

TIP

To change the color of the border around your video window, start playback automatically, display the movie in full-screen mode, or tweak several other details, you need to adjust the markup (see the bolded line in the code above). For the complete scoop, check out http://tinyurl.com/2kxnv3.