HTML5 Doctor » multimedia http://html5doctor.com helping you implement HTML5 today Wed, 02 Mar 2016 08:08:54 +0000 en-US hourly 1 Taking Web Audio Offline in iOS 6 Safari https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/ https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/#comments Tue, 27 Nov 2012 13:30:20 +0000 http://html5doctor.com/?p=4812

Related Posts:

]]>
Playing cached audio for offline use on iOS Safari has long been a challenge that has proved to be mission impossible. But with the advent of the (WebKit-only) Web Audio API, it is now finally achievable — although you still need to jump through a few hoops.

The bad news is that you still can’t cache an MP3 file using Application Cache and then simply load it using an XmlHttpRequest. Safari on iOS 6 will cache the MP3 but then refuse to play it and fail silently (how useful!).

But all is not lost…

Base64 to the Rescue

Because the Web Audio API offers developers direct control over the AudioBuffer, you can now convert data formats on-the-fly and feed them directly to the Web Audio API for playback. For example, if you encode an MP3 file as a Base64 string, you can then decode it to an ArrayBuffer and convert the raw audio data.

Encoding an Audio File

You can easily convert an MP3 file to a Base64 string using OpenSSL. If you are on Mac OS X, it comes pre-installed, so just open up Terminal.app and type the following command:

openssl base64 -in [infile] -out [outfile]

Make sure to replace [infile] with the path to your MP3 and [outfile] with your chosen destination for the encoded data.

This will output a Base64-encoded string representation of your sound file. You can then cache the string using any form of web storage you choose (e.g., Application Cache, localStorage, or webSQL).

Base64 to ArrayBuffer

In order to decode the Base64 string back into an ArrayBuffer, you’ll need to use a custom method. Check out Daniele Guerrero’s base64-binary.js as a good script that can be used exactly for this purpose. It decodes a Base64 string into a Uint8Array typed array and stores it in an ArrayBuffer.

Once this is done, you can simply decode the audio data using the Web Audio API’s decodeAudioData() method:

var buff = Base64Binary.decodeArrayBuffer(sound);

myAudioContext.decodeAudioData(buff, function(audioData) {
  myBuffer = audioData;
});

Once you have the audio data decoded, pass it to your audio buffer source and play the sound:

mySource = myAudioContext.createBufferSource();
mySource.buffer = myBuffer;
mySource.connect(myAudioContext.destination);
mySource.noteOn(0);

Full Demo and Source Code

Check out the online demo and source code for a complete example of the techniques discussed in this article.

Browser Support

Currently the demo works in Safari 6, Chrome Desktop, and iOS 6 Safari. The technique has potential to work in any browser that supports Web Audio API, so hopefully Chrome Mobile can soon add support as well.

The W3C is currently pursuing the Web Audio API as a standard.

Taking Web Audio Offline in iOS 6 Safari originally appeared on HTML5 Doctor on November 27, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/feed/ 11
Multimedia Troubleshooting https://stevefaulkner.github.io/html5doctored/multimedia-troubleshooting/ https://stevefaulkner.github.io/html5doctored/multimedia-troubleshooting/#comments Tue, 31 Jul 2012 13:30:51 +0000 http://html5doctor.com/?p=4711 While I was researching HTML5 multimedia-related topics for my book, HTML5 Multimedia: Develop and Design, I noticed a number people struggling to get HTML5 audio and video working in different scenarios. From Twitter to Stack Overflow, the same questions kept cropping up, so I've put together a list of the most common problems (and some not so common) and their solutions (if there is one!).

]]>
While I was researching HTML5 multimedia-related topics for my book, HTML5 Multimedia: Develop and Design, I noticed a number people struggling to get HTML5 audio and video working in different scenarios. From Twitter to Stack Overflow, the same questions kept cropping up, so I’ve put together a list of the most common problems (and some not so common) and their solutions (if there is one!).

In most cases, the problems and solutions apply to both audio and video. I’ll note when something is specific to one or the other.

Before I go any further, if you aren’t aware of how you can actually go about adding audio and video to your website via HTML5, you can read a number of other articles on this site to get you up to speed. covered the video element, and Mark Boas covered native audio in the browser and HTML5 Audio – The State of Play.

In addition, I covered the same topics, video and audio, as part of a series over on the .

Browser Support

This is one of the first things you should check: Does the browser you’re using actually support the type of media file you’re trying to play? It’s simple enough to forget which browsers support which file types, so I’ll refresh your memory here.

Audio

  • Firefox supports Ogg Vorbis and WAV
  • Opera supports Ogg Vorbis and WAV
  • Safari supports MP3, AAC, and MP4
  • Chrome supports Ogg Vorbis, MP3, WAV, AAC, and MP4
  • Internet Explorer 9+ supports MP3, AAC, and MP4
  • iOS supports MP3, AAC, and MP4
  • Android supports AAC and MP3

In order to support all of the browsers mentioned above, it’s advisable to serve your audio file in Ogg Vorbis, and MP3. For example:

<audio controls> 
   <source src="myAudio.ogg" type="audio/ogg">
   <source src="myAudio.mp3" type="audio/mp3">
</audio>

Video

  • Firefox supports Theora Ogg and WebM
  • Opera supports Theora Ogg and WebM
  • Safari supports MP4
  • Chrome supports Theora Ogg, MP4, and WebM
  • Internet Explorer 9+ supports MP4 and WebM (requires a plugin)
  • iOS supports MP4
  • Android supports MP4 and WebM (2.3+)

In order to support all of the browsers mentioned above, you should serve your video file in both WebM and MP4 using the source element. For example:

<video controls>
   <source src="myVideo.mp4" type="video/mp4">
   <source src="myVideo.webm" type="video/webm">
</video>

MIME Types

Even if you have the correct media file for the browser, it’s possible that your server doesn’t have the correct MIME type set up. MIME types tell the server how to handle the different file types. If you’re using something akin to Apache and you know your stuff, head to the .htaccess file and add the following for audio support:

AddType audio/ogg ogg AddType audio/ogg oga AddType audio/wav wav AddType audio/mpeg mp3 AddType audio/mp4 mp4 AddType audio/mp4 mpa

And similarily for video support:

AddType video/webm webm AddType video/mp4 mp4 AddType video/ogg ogg AddType video/ogg ogv

If you don’t have access to your server’s .htaccess file, your control panel should have an option somewhere that allows you to view and add MIME types.

If you have a Windows server, then you may need to add the MIME types to IIS, either using the IIS Manager or in the web.config file.

File Conversion

It’s quite possible that a client has sent you a media file and you’ve determined its MIME type from its file extension. It’s possible, however, that the file wasn’t encoded correctly. It could, for example, be a perfectly valid MP4 file, but for some reason some browsers have trouble playing it. If this happens, you’re better off encoding the file yourself using a tool such as Miro Video Converter or Media Converter so you can be sure of the correct encoding.

Additionally, some files, especially MP4 files, don’t always play in a browser that is supposed to support them. This is due to the fact that MP4 (also known as H.264) files can be encoded according to different “profiles”. If the file in question is encoded in a profile that the browser doesn’t support, then naturally it won’t work. If this happens to you, try to ensure that the file is encoded according to the Baseline profile which is more likely to be supported than any of the more advanced ones. In my experience, using a tool like Miro ensures that the MP4 file will work just fine in supporting browsers.

If you need to support Firefox 3.6 and lower, you’ll also need to convert your audio files to Ogg and add them as an extra <source> for the <audio> element.

MP4 Files That Don’t Start Playing Until Fully Downloaded

Usually HTML5 audio and video players will allow the user to start playing a media file before it has fully downloaded (as long as it actually has something to play!). Sometimes this isn’t the case with an MP4 file, where the browser waits to download the entire file before making it available to play. This is due to an encoding issue.

Sometimes MP4 files are encoded with the file index (which contains information on the file such as it’s duration) placed at the end of the media file rather than at the beginning. This index contains the metadata that the browser requires in order for it to offer progressive download. If this index is at the end, it knows nothing at all about the file and therefore has to wait until it receives the index.

If this happens to you, there’s a simple fix called the QTIndexSwapper by Renaun Erickson that you download to your computer and run on the file that simply moves the index to the start of the file and saves it.

Getting Your Attributes Right

This might seem a little obvious, but it’s amazing how many questions I see on Stack Overflow where people are wondering why a certain function isn’t working when they’re using attributes that no longer exist. A prime example of this is the autobuffer attribute on both the <audio> and <video> elements, which was replaced by the preload attribute as far back as .

People seem to forget that HTML5 is not yet finalised (although large parts of it are quite stable) and that anything you read might be out of date. It’s worth checking the W3C HTML5 specification and also When Can I Use? to view browser support.

Volume Control in Firefox 11+

This is an problem that has cropped up recently. Some of you may have noticed that the volume controls have disappeared from the audio player in Firefox 11+. True, you can mute it, and the volume controls are still controllable via the keyboard’s up and down keys, but the volume slider itself was removed due to two bugs. I assume this will return in the future, but for now, in case you were wondering what happened to them, it’s not your fault. (You can, of course, use the Media API to build your own set of custom controls.)

Plugins Required

One of the biggest selling points of HTML5 audio and video is that no third-party plugins — such as Flash — are required in order to play multimedia files, as long as the browser in question supports it.

Unfortunately, this is not strictly true, as both Internet Explorer (9+) and Safari do require Microsoft Media Player and Apple QuickTime, respectively, to be installed in order for them to be able to play HTML5 audio and video files.

Video and Fullscreen

An oft-requested requirement for HTML5 video is the ability to play in fullscreen mode. The HTML5 specification has nothing to say on this, but a separate specification for a Fullscreen API is currently under work, with experimental versions available in some of the major browsers.

The following browsers go some way to supporting the Fullscreen API, albeit using their own vendor specific versions:

  • Chrome 19+
  • Firefox 12+
  • Safari 5.1+

There is also the screenfull.js JavaScript polyfill that enables this functionality for a limited number of browsers.

Internet Explorer 9+ Ignores Your Poster Image

If you have a HTML5 video defined with a poster image (using the poster attribute), you might be surprised when Internet Explorer 9 completely ignores it unless you have set the preload attribute to be none.

Since Internet Explorer was one of the last browsers to support HTML5, we all grew accustomed to the other browsers’ treatment of the poster attribute: if it’s specified, display that image until the user starts to play the video. Internet Explorer 9 doesn’t do this. It only displays the image contained within the poster attribute if it has nothing else to show, so if the first frame of the video has been loaded (with preload set to auto — the default value — or metadata), then it uses this regardless of what’s in the poster attribute.

This appears to be a case of Internet Explorer interpreting the specification in its own way and doing something different to all other browsers. Internet Explorer 10 also currently exhibits the same (mis)behaviour.

Accessing Webcams and Microphones

The ability to access peripheral devices such as microphones and webcams was always in the minds of the HTML5 specification writers when they added the <device> element. This has since been removed and replaced with the more thorough getUserMedia API, which allows access to such media devices.

The API itself is easy to use, but browser support is currently quite limited. Opera is currently the only browser with an implementation, supporting only video, but you can already see what it can do. Internet Explorer 10 will follow suit, and it will soon appear in Firefox Nightly.

Summary

This ends my round up of gotchas that you may encounter when working with HTML5 audio and video. Of course, it doesn’t cover everything, and I’m sure there are issues that you may have come across that haven’t been mentioned here. If you have, please do add them below in the comments, with their solution if possible, or if not, I or one of the other HTML5 Doctors will try to help.

Multimedia Troubleshooting originally appeared on HTML5 Doctor on July 31, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/multimedia-troubleshooting/feed/ 23
HTML5 Audio — The State of Play https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/ https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/#comments Tue, 08 May 2012 14:00:24 +0000 http://html5doctor.com/?p=4628 Guest doctor Mark Boas returns with a follow up to his 2009 article Native Audio in the Browser, which covers the basics of HTML5 audio. Read the original if you want to get a feel for the <audio> element and associated API. If not, get comfortable and dive deep to learn about the current state of play for HTML5 audio.

]]>
This is a follow up to my 2009 article Native Audio in the Browser, which covers the basics of HTML5 audio. It may well be worth reading if you want to get a feel for the <audio> element and associated API.

Now, two and a half years later, it’s time to see how things are progressing. With many new advanced audio APIs being actively worked on and plenty of improvements to the existing native audio we all know and love, it’s certainly an exciting time to revisit the heady world of <audio>.

A good way of understanding how the land lies is by going through a few use cases. That’s what I’ll attempt to do in this post.

So how do we get started? Well, there are a few things we need to do to prepare the ground. Let’s tackle MIME types first.

MIME Types

MIME types (also known as Internet Media Types) are a way of defining file formats so that your system knows how to handle them.

Server Side

First things first: your media server should be configured to serve correct MIME types. In the case of the Apache web server, this means adding the following lines to your .htaccess file:

# AddType TYPE/SUBTYPE EXTENSION
AddType audio/mpeg mp3
AddType audio/mp4 m4a
AddType audio/ogg ogg
AddType audio/ogg oga
AddType audio/webm webma
AddType audio/wav wav

Client Side

When defining sources in your code or markup, you can also specify the MIME type, which will help the browser identify the media correctly.

To set up HTML5 audio in the most robust manner, you could write something like this:

<audio>
   <source src="elvis.mp3" type='audio/mpeg; codecs="mp3"'>
   <source src="elvis.oga" type='audio/ogg; codecs="vorbis"'>
   <!-- add your fallback solution here -->
</audio>

Here we define the element and the sources to use. The browser will only pick one. It won’t play both. In this code, we also place a fallback solution after the <source> elements.

Along with the source, we specify a type attribute. Although not strictly necessary, this attribute allows the browser to know the MIME type and the codecs of the supplied media before it downloads it. If not, supplied the browser will guess and take a trial-and-error approach to detecting the media type.

Cool. So now we know how to define our audio sources, and the browser will happily pick the first source that it supports. But what if we want to supply the correct source in a more dynamic manner?

Knowing in Advance: canPlayType Can Help, Probably

Fortunately the audio API provides us with a way to find out whether a certain format is supported by the browser. But first, here’s a quick recap on how we manipulate the audio element via the API.

If you mark up your element in HTML as we did in our previous example, you can grab the <audio> element by doing the following:

var audio = document.getElementsByTagName('audio')[index];

// or, if you gave it an id attribute
var audio = document.getElementById('my-audio-id');

Alternatively, you can also create your element entirely in JavaScript:

var audio = new Audio();

Once you have your audio element, you’re ready to access its methods and properties. To test format support, you can use the canPlayType method, which takes a MIME type as a parameter:

audio.canPlayType('audio/ogg');

You can even explicitly include the codec:

audio.canPlayType('audio/ogg; codecs="vorbis"');

canPlayType returns one of three values:

  1. probably,
  2. maybe, or
  3. “” (the empty string).

The reason we have these odd return types is because of the general weirdness surrounding codecs. The browser can only guess at whether a certain codec is playable without actually trying to play it.

So to test for support, you could do this:

var audio = new Audio();
  var canPlayOgg = !!audio.canPlayType && audio.canPlayType('audio/ogg; codecs="vorbis"') != "";

All we’re doing here is checking that canPlayType is supported (!! effectively casts to a boolean) and then checking that canPlayType of our chosen format doesn’t return an empty string.

Current Browser Codec Support

Let’s check the codec support in the current crop of modern browsers.

Desktop browser audio codec support
Desktop Browser Version Codec Support
Internet Explorer 9.0+ MP3, AAC
Chrome 6.0+ Ogg Vorbis, MP3, WAV†
Firefox 3.6+ Ogg Vorbis, WAV
Safari 5.0+ MP3, AAC, WAV
Opera 10.0+ Ogg Vorbis, WAV

† WAV since Chrome 9

Mobile browser audio codec support
Mobile Browser Version Codec Support
Opera for Android 14.0+ Device-dependent††
Mobile Safari (iPhone, iPad, iPod Touch) iOS 3.0+ MP3, AAC
Android Stock browser 2.3+ Device-dependent††
Chrome for Android all Device-dependent††
Firefox for Android all Device-dependent††
Firefox OS ? ?
Windows Phone ? MP3, AAC
Blackberry 6.0+ MP3, AAC

†† mobile browsers generally use codecs on the host operating system. Various versions of Android include different codecs. Generally, mp3 and Ogg Vorbis can be assumed. See Supported Media Formats in official Android documentation for more.

The good news is that at the time of writing, it’s estimated that around 80% of browsers now support HTML5 audio.

The bad news is that there is still no consensus on which codec to support, so you’ll need to provide both MP3 and Ogg Vorbis sources in order to take full advantage of HTML5 audio.

Containers, Formats, and File Extensions (oh, and MIME types again)

Above, I’ve referred to the audio formats as they’re commonly known, but technically we should refer to their container format. (A container can contain more than one format — e.g., MP4 can contain AAC or AAC+.)

Container Format(s) File Extensions MIME Type Codec String
MP3 MP3 .mp3 audio/mpeg mp3
MP4 AAC, AAC+ .mp4, .m4a, .aac audio/mp4 mp4a.40.5
OGA/OGG Ogg Vorbis .oga, .ogg audio/ogg vorbis
WAV PCM .wav audio/wav 1

We have <audio> and we’re not afraid to use it!

Okay, we’ve done the minimum amount of work to get our audio element set up and playable. What else can we do? At the moment, we’re relying on the browsers’ default audio players, each of which looks and works a little bit differently than the rest. Perhaps we’d like to customise the experience and create our own. To help us do that, the <audio> element supports several different properties exposing its current state.

Some of the more commonly used properties:

Property Description Return Value
currentTime playhead position double (seconds)
duration media duration double (seconds); read-only
muted is volume muted? boolean
paused is media paused? boolean
volume volume level double (between 0 and 1)

Using these properties is pretty straightforward. For example:

var audio = new Audio();
var duration = audio.duration;

The variable duration now holds the duration (in seconds) of the audio clip.

Buffering, Seeking, and Time Ranges

The situation is improving in this area, as browser makers start to implement key parts of the spec.

The API provides attributes called buffered and seekable that can be used in situations where we want to ascertain which part of the media has been buffered, preloaded, or is ready to be played without delay.

Let’s first take a look at the buffered and seekable attributes. Both return a TimeRanges object. The TimeRanges object is a list of time periods containing start and end times that can be referenced by their indexes.

The buffered Attribute

The buffered attribute will return the time ranges that have been completely downloaded. A little bit of a code:

// returns TimeRanges object of buffered media
var buffered = audio.buffered;

// returns time in seconds of the last buffered TimeRange
var bufferedEnd = audio.buffered.end();

The TimeRanges Object

The TimeRanges object contains data on the parts on buffered media in the form of one or more — you guessed it — time ranges. A TimeRanges object consists of these properties:

  1. length — number of time ranges
  2. start(index) — start time in seconds of a particular time range
  3. end(index) — end time in seconds of a particular time range

You may be wondering in what situation the TimeRanges object would contain more than one time range. Imagine the user clicks forward to a portion of unbuffered media. The idea is that the media would then start buffering from that point, and you’d have two time ranges:

------------------------------------------------------
|=============|                    |===========|     |
------------------------------------------------------
0             5                    15          19    21

So in this case:

  • audio.buffered.length returns 2
  • audio.buffered.start(0) returns 0
  • audio.buffered.end(0) returns 5
  • audio.buffered.start(1) returns 15
  • audio.buffered.end(1) returns 19
  • audio.buffered.end() returns 19

Note that if the user is actively seeking through the media throughout the buffering process, a contiguous buffered progress bar actually makes little sense. Also consider that some browsers will read part of the end of the file to establish duration and so create two time ranges almost immediately. Now you’re starting to appreciate why making an accurate buffered progress bar is a little tricky!

You can check out TimeRanges in real-time using this handy HTML5 Media Event Inspector.

Seeking and Seekable

Seeking is the act of looking forward (or backward) in a media file. This usually happens when a section of media is requested before it’s finished loading.

The seeking attribute can be used to determine whether that part of the media is being actively “seeked”. When it returns true, the portion of the media the user requested is still being loaded.

To recap a little, the buffered property tells us what’s been downloaded and is often used as an indication of what part of the media can be directly played. If the browser supports it, however, it may make more sense to use the seekable attribute to determine which parts of the media can be jumped to and played immediately.

seekable returns a TimeRanges object of time ranges that can be played immediately. This uses a technology known as byte-range requests, which allows part of the content to be requested over HTTP. In short, we don’t have to load all the data prior to the desired part in order to play it.

An example:

// Is the player currently seeking?
var isSeeking = audio.seeking;

// Is the media seekable?
var isSeekable = audio.seekable && audio.seekable.length > 0;

// Time in seconds within which the media is seekable.
var seekableEnd = audio.seekable.end();

Time ranges can be confusing. audio.seekable.end() actually tells us the end point of the last time range (not the end point of all seekable media). In practice, though, this is good enough, as the browser either enables range requests or doesn’t. If it doesn’t, then audio.seekable will be equivalent to audio.buffered, which will give a valid indication of the end of seekable media.

Note that media being in a “seekable” state is different than media being in a “buffered” state. Media doesn’t have to be buffered to be seekable.

Buffered and seekable data can be useful information, but it would be too easy if there weren’t a few gotchas.

  1. Preloading is not supported in all older audio-capable browsers (Opera 10/Firefox 3.6).
  2. The buffered attribute is not always supported (Blackberry PlayBook).
  3. Not all HTML5 browsers allow byte-range seeking — for example, Safari on Windows. In this case, you can still seek within the downloaded content. It downloads from the start until the end, as does Flash.

If you want to deliver the best possible solution to your users, you’ll need to feature test.

A Note about Preloading

I mentioned the preload attribute in the previous article. This attribute accepts three possible values:

  1. none — Do not preload any media. Wait for a play event before downloading anything.
  2. metadata — Preload just the metadata. Grab the start and the end of the file via range-request and determine the duration.
  3. auto — Preload the whole file. Grab the start and the end of the file to determine duration, then seek back to the start again for the preload proper.

When it comes to preloading, remember that it’s a request or hint to tell the browser how you’d like to preload the media. The browser is not under any obligation to fulfill that request. For this reason, certain browsers may handle these requests differently.

Well-Played

It’s worth mentioning the played property in passing. This property tells us which time ranges have been played within the media. For example:

// returns a TimeRanges object
var played = audio.played;

Media Events

Underpinning both the native audio and video APIs is a comprehensive set of events. A full list can be found at the WhatWG version of the spec.

Attaching handlers to media events allows you to easily react to changes in state. For example, it might be useful to update the time info in a custom-built player each time the timeupdate event occurs.

A quick summary of the more commonly used media events:

Event Description
durationchange The duration attribute has been updated.
ended Playback has stopped as the end of the media was reached.
pause The media playback has been paused. Note there is no stop event.
play The media has started playing.
timeupdate The current playback position changed (usually every 250ms).
volumechange The volume changed.

Other useful events:

Event Description
canplay The media can be played but may need to pause while the file is downloaded.
canplaythrough At current download rates, it is estimated that the media can be played from start to finish without pause.
progress The browser is fetching the media data (usually every 250ms).

Again, the HTML5 Media Event Inspector is your friend.

Additionally, you can test browser support by using areweplayingyet.org. It’s worth checking out the code behind the tests to understand the goings-on under the hood.

Streaming

Streaming audio is a common requirement. This is an area that until recently has been dominated by Adobe’s Flash technology. Proprietary server technologies and protocols are well-established. One of the leading examples of this is Adobe’s Real Time Messaging Protocol (RTMP). However, current browsers only support streaming over HTTP, and so something like Flash is required to process RTMP streams.

Currently, audio-enabled browsers only support SHOUTcast and Icecast servers that stream audio over HTTP. SHOUTcast is propriety and allows streaming of MP3 and AAC files only, while Icecast is non-propriety and supports Ogg Vorbis as well as MP3 and AAC.

Stream AAC MP3 Ogg Vorbis Native Support
Icecast Yes Yes Yes Yes
SHOUTCast Yes Yes No Yes
RTMP Yes Yes No No (requires Flash)

An Evolving Spec (Or, “Whoa, this thing is moving!”)

As the audio spec is still evolving, there are a couple of inconsistencies in browser implementations to watch out for. These generally affect older browsers.

The load Method

Until fairly recently, the load method was required in order to tell the browser about a change in the media source and to get it to update appropriately. Now, media.load() causes the element to reset and to start selecting and loading a new media resource from scratch.

So for older browsers, such as Firefox 3.6, in order to change the media source, you’ll not only need to change the source value but also issue a load command:

var audio = new Audio();
audio.setAttribute("src","mynew.mp3");
audio.load(); // required for 'older' browsers

When Browsers Go Off-Spec

When creating cross-browser solutions, it’s useful to know which browsers follow the W3C spec to what extent and how they deviate.

Autoplay and Volume

iOS and Blackberry devices ignore the autoplay attribute and media element volume changes, whereas Android supports autoplay but not volume changes.

Effectively, on Blackberry and iOS devices, autoplay functionality is disabled as both require a user-initiated event to “kick it off”. This has the unfortunate side-effect that any audio suffers a delay between user interaction and playback.

To mitigate against these issues, you may want to take a look at Doctor Remy Sharp’s excellent article on Audio Sprites and fixes for iOS.

Simultaneous Playback of Multiple Audio Elements

A particular annoyance for developers of anything but the most simple audio web apps: not all browsers will play multiple audio elements simultaneously. This is a particular problem for games developers. Again, we see this issue with iOS and Blackberry devices.

Operating System Dependence

Safari (5+) relies on Quicktime being installed. This is rarely a problem unless you are running it on Windows.

Internet Explorer (9+) relies on the codecs being present at the operating system level. As it only runs on Windows, this is fortunately almost always the case.

What’s New?

There are a few new features and whole new APIs being specified for web-based audio, so let’s take a look at what’s around the corner.

A Change of Pace

A couple of noteworthy upcoming features are playbackRate and defaultPlaybackRate. As you can probably imagine, these fellas let us alter the speed and direction of playback. This functionality could be used for fast-forward and rewind functions or perhaps to allow users to tweak the playback speed so they can fit more podcasts into their day.

  • audio.playbackRate returns 1 at normal speed and acts as a multiple that is applied to the rate of playback. For example, setting playbackRate to 2 would double the speed, while setting it to -1 would play the media backwards.
  • audio.defaultPlaybackRate is the rate at which the audio will play after you pause and restart the media (or issue any event for that matter).

Media Fragments

Currently, if we wish to reference some part of a media file, we often first have to download at least some of the media we don’t actually need. The W3C Media Fragments proposal was created to address this issue and others, such as the retrieval of an area of video or just the associated text track. In the case of audio, it will allow us to specify which parts we want to download using parameters on the source URI.

Advanced Audio APIs: The Future Sound of Browsers

When it comes to more advanced audio functionality, Mozilla was first to enter the fray with an early experimental Audio Data API for Firefox. This was intended to facilitate audio manipulation via JavaScript and created a platform for low-level tinkering.

Not to be outdone, Google released the Web Audio API for Chrome and put it forward as a W3C proposal. The Web Audio API is a higher-level implementation that takes an audio-node based approach and provides many useful functions.

Both implementations address the desire by developers to do more with audio — to create, manipulate, analyse, and mix audio on the fly. In effect, we may one day be able to do in a browser anything we can currently do with native applications.

So what if we want to play with advanced audio in the browser? Well, two separate implementations currently exist. If you want to write applications that use both APIs in any reasonable way, you need third-party bridging libraries to abstract away the differences.

Also fairly new on the scene is Mozilla’s MediaStream Processing API, which takes another approach to audio and video streams to allow us to manipulate at both high and low levels.

In fact, using advanced APIs and taking advantage of the speed of modern JavaScript engines, we can even write decoders for unsupported codecs. Currently, we have the JSMad MP3 decoder and the lossless Alac.js decoder. Apparently, FLAC and AAC are in the pipeline. There is hope, then, that in the future, we may not have to worry about which browsers are supporting which formats.

For those curious about advanced web audio, I wrote about the differences in approaches and the different libraries that allow us to write cross-browser solutions in HTML5 Audio APIs: How Low can we Go?

The good news is that all relevant parties are talking, and things seem to be buzzing on the W3C Audio Working Group. It looks like everyone is coming together to put their ideas into a unified Audio Processing API, which is rapidly approaching publication as a Web Standard.

Summary

Although browser implementations of the current HTML5 audio spec are improving, there are still a few issues to watch out for when creating comprehensive cross-browser solutions. You certainly need to be aware of browser limitations on platforms like iOS. Hopefully, as support matures, these issues will disappear.

Positive news on the “advanced audio” front too: a new standard is being established, and we’re close to get a unified spec for browser makers to work from. In the meantime, JavaScript libraries are available to help bridge the gaps between existing implementations.

There are also signs that we may be seeing the end of the requirement for different browser-dependent codecs. Opera Mobile already supports MP3 where the underlying OS supports it, and Mozilla look like they may enable this too. If this option exists for mobile browsers, it’s not a huge stretch to imagine that desktop browsers will follow suit.

So lots happening and lots already achieved. The rough edges of existing browser implementations are being smoothed, consensus and standards are being forged, and we can see the foundations of some very exciting new technologies being established.

The future of web-based audio looks bright!

HTML5 Audio — The State of Play originally appeared on HTML5 Doctor on May 8, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/feed/ 32
It's Curtains for Marital Strife Thanks to getUserMedia https://stevefaulkner.github.io/html5doctored/getusermedia/ https://stevefaulkner.github.io/html5doctored/getusermedia/#comments Tue, 07 Feb 2012 14:56:03 +0000 http://html5doctor.com/?p=4335 HTML5 (or now, the WebRTC spec) gives us getUserMedia, a way for JavaScript to access streams from a device's camera and microphone. Find out how to use it and normalise the syntax differences between Opera and Chrome with the gUMshield.

]]>
True story: I was tasked by the lovely Mrs Lawson to buy some curtains that match our carpet during the January sales. I dutifully did so — and had to return to the shop straight away because they didn’t match at all. Mrs Lawson accompanied me, and with a withering glance at her incompetent mate, immediately found some correctly hued fabric, and all was well.

But what’s a middle-aged colour-blind bloke to do? I had early in the curtain procurement process decided against cutting a hole in the carpet in order that I may take a sample with me. (All other mistakes aside, this was a correct decision.)

So, in order to ensure that I would never again repeat the mistake, I set out to make an app that would allow me to capture the colour of an image straight from my camera. Of course, it had to be a web app rather than a native app, because we’re web angels, not proprietary devils.

getUserMedia

getUserMedia is an API that gives a web page access to a user’s camera and microphone via JavaScript. It’s supported in Opera 12 and Opera Mobile 12 for Android, and WebKit in Chrome Canary builds (instructions).

Like many other APIs, it’s not part of the “real” HTML5 spec. It started life as the HTML5 <device> element, then got moved into the W3C as part of the webRTC specifications. But let’s not taxonomise when we could be having fun.

The first thing we need to do when using super-cool new UIs is detect whether it’s supported:

 if (navigator.getUserMedia) {
  // do something cool
} else {
  // fallback code
}
Basic usage of getUserMedia

For this article, our “do something cool” will be to grab the dominant colour of the current input stream from the camera. As a fallback, we have several options.

One option, if we’re using the default Android browser, is to show a form that automatically starts the camera when focussed:

<form enctype="multipart/form-data" method="post">
  <input type="file" accept="video/*;capture=camera" />
</form>
Fallback code for Android

There’s also the capture attribute, a proposed extension from the W3C Device API Media Capture API that tells a user agent where to get the input data. Android extends the accept attribute. See more in David Calhoun’s Device API article. Alternative capture arguments are camcorder (for video), microphone, and filesystem.

Browsers that don’t understand the still-draft Media Capture API will simply ignore the capture attrbute and prompt the user to browse to a file on their file system for uploading.

Users on iOS are out of luck, as their devices don’t allow access to the file system.

Differences Between the Media Capture API and getUserMedia

Robin Berjon, co-chair of the Device API (DAP) Working Group explains: The markup-only Media Capture API is a simpler, low-hanging-fruit version that can work easily for a lot of use cases. It also has a very simple security model (just a file upload).

In fact, it works exactly like <input type=file>, except that it knows to allow the user to grab a pic from the camera by default instead of hitting the filesystem. But just like with <input type=file>, once a picture has been taken (i.e., a file selected), you can access it and read from it using the File API, which means you can stuff it in an <img> or a <canvas> and do nasty things to it without annoying any faraway server.

But of course, if it’s part of a form and you submit it, it gets submitted just like a regular file upload.

The thing is, though, it’s always a snapshot. Even if you use it to take a video (which you can), the page only gets it after you’ve finished shooting. With getUserMedia (gUM), you get the live stream, which you can modify, record, or stream elsewhere. The gUM approach is more powerful but more complex, and it has more severe security issues.

getUserMedia API

Let’s assume (because we’re optimists) that your user has a getUserMedia-enabled device. The API is nice and simple, as all Web APIs should be.

navigator.getUserMedia accepts two required arguments and an optional third.

The first argument tells the device which media you require access to, and it’s passed as a JavaScript object. So, if you only require access to the microphone, the first argument would be {audio: true}; for video-chatting, you would use {audio: true, video: true}.

The device decides which camera to use: User agents are encouraged to default to using the user’s primary or system default camera and/or microphone (as appropriate) to generate the media stream.

A previous version of the specification allowed hints to user agents about which camera to use. The API could specify “user” (the front camera on a phone) or “environment” (the rear camera on a phone). Debate continues about whether to reinstate this (read the ongoing conversation). One argument against is that letting sites know what cameras a device has could help Dr Malice of Evil Corp. fingerprint users after luring them to his site (which I find to be overly-cautious). Harald Alvestrand poses a conundrum: conferencing units may have a room camera, a document camera and a lectern camera, neither of which is attached to the physical box; which one of these is front?

But let’s not worry at the moment. Devices with more than one camera generally have a mechanism that allow the user to choose which one is used, so this gives the user control. Note also that the spec says User agents may allow users to use any media source, including pre-recorded media files.

The second argument is the success callback, the function to be executed on success, assuming that the user allows access and the device supports your request.

There is an optional third argument. This is the failure callback, the function to be executed if something went wrong. It’s optional, but only optional in the sense that washing your hands before you eat is optional: if you don’t do it, you leave yourself open to all sorts of bugs and your mum will shout at you.

Of course, it’s important to do feature detection before making an API call to ensure that the browser and device are capable, but even if feature detection succeeds, there is still much that can cause failure. For example, the user could deny permission or turn off the camera via a hardware switch, or the device itself could disable the camera.

So here’s how we recommend you use the API:

navigator.getUserMedia({audio: true, video: true}, success, error);

function success(stream) { 
  // ... use 'stream' ... 
} 

function error(){ 
  // display fallback content 
}
Using the gUM API

To check whether it’s working correctly, we can attach the output of the camera’s stream to the input of an HTML5 video on the page, like this:

<video autoplay></video>
<script>
if (navigator.getUserMedia) {
  navigator.getUserMedia({audio: true, video: true}, success, error);
  function success(stream)
  { 
    // ... use 'stream' ...
    var video = document.getElementsByTagName('video')[];
    video.src = stream; 
  }
  // ...
</script>
Streaming captured video to an HTML5 <video> element

Differences Between Webkit and Opera

The two rendering engines that implement getUserMedia do so in two different ways. Hopefully, they’ll harmonise when the features reach the released browsers.

The differences:

  • WebKit uses a prefix — navigator.webkitGetUserMedia — while Opera doesn’t.
  • WebKit implements the options according to an old version of the spec, in which audio and video were passed as strings:
    navigator.webkitGetUserMedia("video, audio", /* ... */)
    whereas Opera implements the most recent version of the specification which uses JavaScript objects:
    navigator.getUserMedia({video: true, audio: true}, /* ... */)
    (Added June 2012: Chrome 20+ uses the ({video: true, audio: true} syntax.)
  • WebKit attaches the resulting stream like this:
    video.src = window.webkitURL.createObjectURL(stream);
    which is according to the current version of the spec. Opera uses:
    video.src = stream;
    and has proposed simplifying the spec (but discussion continues).

But this fragmentation, even though it’s only in experimental browser releases is, like, a total drag, man.

Introducing The gUM Shield

Fortunately, we’ve got your back. Two of the finest minds I know — actually, two of the finest Mikes, Doctor Mike Robinson and Opera’s Mike Taylor — have created a snippet of script that you can copy to shield you from these annoying differences. We’ve named this getUserMedia syntax normalisation script snippet The gUM Shield.

It assumes that there’s a variable called video to which you’ve assigned a reference to the <video> element you’ll stream to. Do this with some mechanism like:

video = document.getElementById('video');

Simply hit the ‘Hub, download it, plug it into your script, and check it out!

Note that it’s experimental. Who knows what’ll happen when Mozilla, Microsoft, and Apple implement it, but please, have a play. Fork it and improve it!

Doing Exciting Things with the Video Stream

So far, we’re only echoing the video stream. But, as you’ll know from Tab Atkins’ guest article video + canvas = magic, if we copy the video into a canvas, we can manipulate it:

var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

ctx.drawImage(video, 0, 0, video.width, video.height,
  0, 0, canvas.width, canvas.height);
Canvas and video magic

A common mistake is assuming that this somehow establishes a “live connection” between the video stream and the canvas. It doesn’t. It only grabs the current frame. So you need to grab the current frame repeatedly in order to replicate a video. The magical number is 15 times a second (or every 67 milliseconds), but a slower frame rate would probably be okay for this demo:

setInterval(function () { 
  ctx.drawImage(video, 0, 0, video.width, video.height,
  0, 0, canvas.width, canvas.height);
},  67);
Live updating of <canvas> from a <video>

See the working demo.

What I want to do now is to grab the dominant colour from the canvas. I’m stealing a demo by Shwetank Dixit (who borrowed from Lokesh Dhakar‘s Color Thief demo). We won’t look at how it determines the dominant colour (because that’s nothing to do with getUserMedia).

Try this in Opera Labs and Chrome Canary!

Unfortunately, this works splendidly in Opera but it occasionally fails in Chrome, and we’re not sure why. (We’ve emailed the Chrome team to ask them.) Apart from the rather anti-climactic end to an article, you shouldn’t be dismayed by this. getUserMedia is only available in experimental builds that have plenty of work to be done before they hit production.

Back to our demo. Once you’ve got the dominant colour, you could prompt the user for a name for that colour (“carpet”, for example) and store that in local storage using its name as a key. Then, when you find a pair of curtains in the shop, you can find their dominant colour and easily compare it with that stored against “carpet” from earlier.

And you can return home, confident of delighting the love of your life with your chromatically appropriate choice of soft furnishings. That’s HTML5: enriching marriages since 2004.

woman says 'hey daddy-o, the curtains really razz my berries, ya dig?'. Man replies 'Baby, I totally dig. Early night?'. A thought bubble shows him thinking 'Thank you, getUserMedia'

Harshing Your Mellow

Things need refining before web apps with getUserMedia are on a par with native applications. At the moment, there is no way of controlling which camera is to be used (and no agreement that a developer should be able to). The camera’s flash mechanism isn’t programmatically controllable, which could harm the user experience. Most importantly are the privacy implications of web pages being able to access your camera. Opera has an experimental privacy UI, but Chrome has no UI yet.

More Demos

See Paul Neave’s HTML5 Webcam Toy and the links at the foot of my Opera Labs article.

Thanks

Thank for help and code are due to Robin Berjon, Shwetank Dixit, Daniel Davis, Lokesh Dhakar, Mike Taylor, Mike Robinson, and .

Addy Osmani’s Polyfill

Added 13 March 2012: Addy Osmani has published a getUserMedia polyfill called getUserMedia.js, which uses Flash if gUM isn’t available. It’s not ready for production yet, as IE is still being tested. Forkers may hit the ‘hub.

It's Curtains for Marital Strife Thanks to getUserMedia originally appeared on HTML5 Doctor on February 7, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/getusermedia/feed/ 28
Video Subtitling and WebVTT https://stevefaulkner.github.io/html5doctored/video-subtitling-and-webvtt/ https://stevefaulkner.github.io/html5doctored/video-subtitling-and-webvtt/#comments Tue, 29 Nov 2011 15:33:59 +0000 http://html5doctor.com/?p=4084 We’ve been able to play video in the browser without a plugin for a couple of years now, and whilst there are still some codec annoyances, things appear to have settled down on the video front. The next step is adding resources to the video to make it more accessible and provide more options to the viewer.

]]>
We’ve been able to play video in the browser without a plugin for a couple of years now, and whilst there are still some codec annoyances, things appear to have settled down on the video front. The next step is adding resources to the video to make it more accessible and provide more options to the viewer.

We currently have no means to provide information about what’s happening or being said in the video, which means the video isn’t very accessible and the user can’t easily navigate to a particular section of the video. Thankfully, there’s a new format specification in the works called WebVTT (Web Video Text Tracks). As of now, it’s only in the WHATWG spec, but the recently established W3C Web Media Text Tracks Community Group should introduce a WebVTT spec to the W3C soon.

You may recall a similar format called WebSRT (Web Subtitle Resource Tracks) that was recently under discussion. WebSRT was renamed to, and has been replaced by, WebVTT.

A WebVTT (.vtt) file is simply plain text containing several types of information about the video:

Subtitles
The transcription or translation of the dialogue.
Captions
Similar to subtitles, but may also include sound effects and other audio information.
Descriptions
Intended to be a separate text file that describes the video through a screenreader.
Chapters
Intended to help the user navigate through the video.
Metadata
Information and content about the video, which isn’t intended to be displayed to the viewer by default, though you may wish to do so using JavaScript.

This article will mostly be talking about subtitles and captions, but it will briefly touch on chapters too.

Beyond the scope of this article but worth mentioning is the text track API, which, amongst other things, denotes how many text tracks there are and which ones have loaded and are ready for use. If you have used this API, let us know.

How to Make and Link to a WebVTT file

All you need to make a WebVTT file is a simple text editor. Type WEBVTT as the first line of the file and save it as a .vtt file. In the future, we expect existing captioning tools such as Universal Subtitles to export to WebVTT format.

WEBVTT
The simplest possible valid WebVTT file

That’s all you need to get started. Next, we have to link to the file in the HTML document. We do this via the <track> element, which is a child of the video element. The <track> element has several optional attributes:

  • the source WebVTT file (src),
  • the language of the track (srclang),
  • a user-readable label, and
  • what kind of track it is. The values of the kind attribute come from the list above (i.e., subtitles, captions, etc.).

In the following example, we’re using a <track> element for subtitles:

<video width="640" height="480" controls>
  <source src="video.mp4" type="video/mp4" />
  <source src="video.webm" type="video/webm" />
  <track src="subtitles.vtt" kind="subtitles" srclang="en" label="English" />
  <!-- fallback for rubbish browsers -->
</video>

A few notes about the attributes:

  • If no kind is specified, the default is subtitles.
  • If the kind is subtitles, then srclang is required.
  • There should not be two tracks of the same kind with the same label.

In the above example, we use a <video> element with two different <src> elements (for cross-browser loveliness). After the sources comes the <track> element. You can have several <track> elements as you might have subtitles, captions, and descriptions all in different languages.

<track> doesn’t presuppose a particular file format. the TTML format, but this format will not be implemented by other browser vendors.

WebVTT Contents

We now know how to make a WebVTT file and how to reference it in an HTML document, but what goes inside it? Within the file, we list what are known as “cues”. The WebVTT file might only have one cue, but it can contain as many as you want. Each cue starts with an ID, followed by the time settings, followed by the text. Each cue is separated by a blank line. Here’s an example of captions:

WEBVTT

1
00:00:01.000 --> 00:00:10.000
This is the first line of text, displaying from 1-10 seconds

2
00:00:15.000 --> 00:00:20.000
And the second line of text
separated over two lines
WebVTT example content

The above example has two cues. Times must be written in hh:mm:ss.mmm format, so the timings in this example occur in the first twenty seconds. The second cue will split the text over two lines automatically.

If you have a segment of text that needs to appear in a karaoke/paint-on caption style, then you can place timers inline with text:

1
00:00:01.000 --> 00:00:10.000
Never gonna give you up <00:00:01.000> Never gonna let you down <00:00:05.000> Never gonna run around and desert you
Karaoke-style captioning

Styling Options

The previous examples specify the minimum configuration you need for subtitling and captioning, but you can style your captions too. Let’s start with the cue settings, which are done on the same line as the time settings:

D:vertical / D:vertical-lr
Display the text vertically rather than horizontally. This also specifies whether the text grows to the left (vertical) or to the right (vertical-lr).
L:X / L:X%
Either a number or a percentage. If a percentage, then it is the position from the top of the frame. If a number, this represents what line number it will be.
T:X%
The position of the text horizontally on the video. T:100% would place the text on the right side of the video.
A:start / A:middle / A:end
The alignment of the text within its box – start is left-aligned, middle is centre-aligned, and end is right-aligned.
S:X%
The width of the text box as a percentage of the video width.

To make use of these settings, put them alongside the time settings, like this:

00:00:01.000 --> 00:00:10.000 A:middle T:50%
00:00:01.000 --> 00:00:10.000 A:end D:vertical
00:00:01.000 --> 00:00:10.000 A:start T:100% L:0%

which would result in something like the following:

Examples of subtitle display

Examples of subtitle display and alignment

Along with the above cue settings, you can use inline styles for text:

Bold text
<b>Lorem ipsum</b>
Italic text
<i>dolor sit amet</i>
Underlined text
<u>consectetuer adipiscing</u>
Ruby text
<ruby>見<rt>み</rt></ruby>

You can even apply a CSS class to a section of text using <c.myClass>Lorem ipsum</c>, giving us many more styling options.

Finally, you can add a declaration representing the name of the voice: <v Tom>Hello world</v>. This declaration accomplishes three things:

  1. The caption will display the voice (Tom) in addition to the caption text.
  2. The name of the voice can be read by a screenreader, possibly event using a different voice for male or female names.
  3. It offers a hook for styling so that, for example, all captions for Tom could be in blue.

Chapters

You can provide a chapter list for the video the same way you would provide subtitles or captions. Start with the same WEBVTT declaration, and then for each cue, declare the chapter number, the start and stop times, and the chapter title:

<track src="chapters.vtt" kind="chapters" srclang="en" />
HTML <track> element for providing chapters to a video
WEBVTT

Chapter 1
00:00:01.000 --> 00:00:10.000>
Introduction to HTML5
WebVTT file containing video chapter markers

Browser Support

One slight glitch with WebVTT: not a single browser currently supports it. All major browsers have started working on implementations, so we should see some results soon. Thankfully, in the meantime, there are several JavaScript polyfills available:

Demo

We’ve put together a quick demo which uses the Playr polyfill. We started using MediaElementJS, but it doesn’t sport as many features as Playr, such as separate lines of text and CSS classes. In the demo, the subtitles start at 2 seconds and 15 seconds and use bold, underline, and custom styles. Here’s the associated WebVTT file.

Conclusion

This article covers the basics of creating a WebVTT file suitable for subtitles or captions for a video. We know how to add cues and chapters and how to add styles and change how the text appears on the video. Although no browser yet supports it, there’s a lot more to come for accessible video, so stay tuned to the W3C Web Media Text Tracks Community Group.

What are your thoughts on WebVTT? Are any of you using it now? How can it be improved?

Finally, let’s thank @silviapfeiffer for taking the time to answer some questions about WebVTT and for her tremendous work in this field.

Reading

Video Subtitling and WebVTT originally appeared on HTML5 Doctor on November 29, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/video-subtitling-and-webvtt/feed/ 16
HTML5 Simplequiz #3: how to mute a video https://stevefaulkner.github.io/html5doctored/html5-simplequiz-3-how-to-mute-a-video/ https://stevefaulkner.github.io/html5doctored/html5-simplequiz-3-how-to-mute-a-video/#comments Fri, 15 Oct 2010 08:35:16 +0000 http://html5doctor.com/?p=2628

Related Posts:

]]>
This is a bit of a special Simplequiz this week. Simon Pieters (@zcorpan), who works on multimedia QA for Opera and is one of those working on the HTML5 spec, asked us to run a quiz that would help the spec writers decide on a new aspect of the language. What power you wield, gentle reader! Over to Simon…

This SimpleQuiz is a bit different to previous SimpleQuizzes, since we’d like to use the result of this quiz to inform a design decision in the HTML5 spec. The question concerns how to mute a video in markup, and how this should be reflected in the DOM.

The use case is wanting to have multiple videos playing at once, but with all but one being muted at a time.

This can be done today by setting .muted = true with script, but it would be more convenient to be able to mute with markup.

The .muted IDL attribute reflects the user setting of muted for the video element — if the user clicks “mute” in the native video controls, then the value of .muted changes, and vice versa. It would make sense for the browser to remember the mute setting for individual video elements on page reload (or later visit), so that the user doesn’t have to re-mute them.

This is where it starts to get hairy if we introduce a content attribute for muting. (Note that code fragments below aren’t real code, just suggestions.)

We could introduce muted="" which is reflected by .muted (i.e. if one changes, so does the other), but this would cause the DOM to mutate during parsing if the remembered setting doesn’t match the markup, i.e. you would get muted="" to appear in the DOM if the video is muted by the user even though there was no such attribute in the markup, which could confuse your scripts or style sheets if it’s not what you expected to happen.

We could introduce defaultmuted="" which is reflected by .defaultMuted, and just let the user setting change .muted, but defaultmuted="" is a bit long and ugly in markup.

We could have muted="" which is reflected by .defaultMuted and let the user setting change .muted, but it might be confusing for some people. On the other hand it is consistent with <input value> and .defaultValue.

What do you think? Which is the best option? Is there another option that is better than any of the above?

HTML5 Simplequiz #3: how to mute a video originally appeared on HTML5 Doctor on October 15, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/html5-simplequiz-3-how-to-mute-a-video/feed/ 32
Video: the track element and webM codec https://stevefaulkner.github.io/html5doctored/video-the-track-element-and-webm-codec/ https://stevefaulkner.github.io/html5doctored/video-the-track-element-and-webm-codec/#comments Thu, 24 Jun 2010 13:45:42 +0000 http://html5doctor.com/?p=2089

Related Posts:

]]>
There are a couple of interesting developments in the world of HTML5 multimedia that you’ll be interested in. The first is the new <track> element (currently only in the WHAT-WG spec due to political stuff).

<track> is a child of a <video> or <audio> element that links to a timed track, or time-based data. The kind of data is set via a kind attribute, which can take values of subtitles, captions, descriptions, chapters or metadata, depending on the type of information you’re adding to your media. These point to a source file containing timed text that the browser will expose via some kind of user interface, if the visitor requires additional data.

This will allow for “write once, use everywhere” accessibility; anyone linking to that file with a <video> or <audio> element that includes the element can access your information.

<track kind=captions src=blah.srt>

The file format is a new format called WebSRT, which competes with about 50 other timed formats, including some W3C formats (hence the omission of <track> from the W3C spec).

Added 9 July 2010: Here’s a readable overview of the SRT format.

Given that the format itself isn’t fully specified yet, it will be a while until we see implementation in browsers. But it’s good to know that there will be an official way to add accessibility information to media. Until then, I have a JavaScript hack to take timed <span>s out of an in-page transcript to superimpose over a video.

WebM video format

The big news of the last month is that Google open-sourced the VP8 video codec that it acquired when it took over On2 Technologies. When combined with the Vorbis audio codec (that Spotify uses) and wrapped in a subset of the Matroska container format, it’s collectively known as WebM.

All YouTube videos are being transcoded to WebM, and Adobe have also announced they will include it in their Flash player. It’s available in an Opera 10.60 beta, a Firefox testing build, and a Chromium dev channel. Even Microsoft have said that IE9 will support it if the codec is installed on the computer.

The VP8 video codec itself is high-quality (Google had said that Ogg Theora wasn’t good enough compression-to-quality for YouTube, but Theora was based on the VP3 precursor to VP8). It’s available for streaming too.

If you want to encode to WebM, you can try the Miro Video Converter utility. Although it doesn’t allow you to optimise settings, it’s very easy to use. As the codec becomes more widespread, expect to see many more tools for content creation, editing, and transcoding.

Once production versions of the browsers are available, you should encode your videos with WebM as the first option, Ogg for older versions of Opera, Firefox and Chrome, falling back to royalty-encumbered H.264 for Safari and links to downloads or a Flash player for legacy browsers:

<video controls>
<source src=video.webm type='video/webm; codecs="vorbis,vp8"'>
<source src=video.mp4 type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
<source src=video.ogv type='video/ogg; codecs="theora, vorbis"'>
<!-- embed Flash here -->
<p>Your browser does not support video; download the <a href="video.webm">WebM</a>, <a href="video.mp4">mp4</a> or <a href="video.ogg">Ogg</a> video for off-line viewing.</p>
</video>

If, however, you’re having problems with the iPad, put the MP4 version first in the <source> element; apparently there’s a bug that causes the iPad only to see the first <source> element.

It’s a long haul, and it’s not over yet, but <track> and .webM show significant progress towards our goal of accessible, open, and royalty-free video playing natively in the browser.

Video: the track element and webM codec originally appeared on HTML5 Doctor on June 24, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/video-the-track-element-and-webm-codec/feed/ 33