HTML5 audio and video tags in different browsers in practice. Mastering HTML5 audio tag Audio player in html web page

With the advent of reasonably fast Internet connections, Flash was the only way to play sounds on websites. But HTML5 will fundamentally change the way sounds are played on the Internet. In this article, I want to tell you in detail about how to use the tag on your sites.

We use

Below is the simplest example of using the tag, it downloads an mp3 file and plays it. Notice the attribute autopaly, which is used to automatically play the sound. However, you should not automatically play sounds on the site, as this will annoy users.

Playing a sound in a loop

Want to loop the sound? The loop attribute will help you do this. But again, don't overuse autoplay and looping if you don't want the user to leave the site prematurely.

Displaying Controls

Instead of playing sounds automatically, which is definitely a bad practice, you should allow some controls to be displayed in the browser, such as volume and play (pause) buttons. This is easy to do by simply adding the attribute controls.

Various file formats

The tag is supported by most modern browsers, but the problem is that different browsers support different file formats. Safari, for example, can play MP3s, but Firefox cannot, and plays OGG files instead. The solution to this problem is to use both formats so that every visitor can hear the sound, no matter what browser they use.

Specify the MIME type of the files

When using different file formats, it's good practice to specify a MIME type for each file to help the browser localize the file it supports. This can easily be done using the attribute type.

For older browsers

What if the visitor is using IE6 or some other prehistoric browser that doesn't support the tag? It's easy: below is the code that will display a message for browsers that do not support the tag.

File Buffering

When playing large files, file buffering may be used. For this you can use the attribute preload. It can take 3 values:
  • none- if you do not want to use the file buffer;
  • auto- if you want the browser to buffer the entire file;
  • metadata- to download only service information (duration of sound, etc.).

Playback control via JavaScript

Controlling the HTML5 audio player via JavaScript is very easy. The following example shows how you can build your basic audio player controls using JavaScript:

That's all for today.
I hope this article helped you understand the basic features of the HTML5 tag. .

Description

Adds, plays and manages audio recording settings on a web page. The path to the file is specified through the src attribute or a nested tag. Inside the container

The list of codecs supported by browsers is limited and is given in Table. one.

Tab. 1. Codecs and browsers
Codec Internet Explorer Chrome Opera safari Firefox
ogg/vorbis
wav
mp3
AAC

For universal playback in the specified browsers, audio is encoded using different codecs and files are added simultaneously through the tag .

Syntax

Attributes

The sound starts playing as soon as the page loads. Adds a control panel to an audio file. Repeats the sound from the beginning after it ends. Used to download a file along with loading a web page. Specifies the path to the file being played.

Closing tag

Required.

HTML5 IE 8 IE 9+ Cr Op Sa Fx

audio

Alexander Klimenkov - Fourteen

Example result in Opera browser shown in fig. one.

Rice. 1. Audio file playback

Browsers

Audio playback controls differ between browsers in their appearance, but the basic elements are the same. These are the play / pause button, track length, elapsed and total playing time, as well as the volume level.

Until recently, embedding sound into a web page was not an easy task. In general, there are , among which some offer smarter and better implementations, but most of the ways limit you to the fact that you need to have a certain browser and certain plugins.

With the advent of Flash technology on the market, this task has been greatly simplified, since the Flash plugin allows you to embed any animation or sound in a page, and the technology is supported by most browsers. But the demand for Flash is gradually fading after the release of innovative devices from Apple: iPhone and iPad. As is known, Apple company fundamentally does not equip its devices with Flash support, and the number of users of products is growing rapidly.

In short, there is some confusion here.

Fortunately, HTML5 has made life much easier for developers, as the technology has an element audio. This element allows you to embed audio files in any web page, as well as implement a control panel through javascript. More importantly, the technology does not require additional plugins, and is supported in almost all browsers, except for early versions (we will talk about browser support later!).

In our today's article, we will tell you about how you can embed sounds using the element audio. We will also learn how to control the playback process through javascript, and also try to tell you about technology support among browsers.

HTML5 Audio element

This item is extremely easy to use. In our example today, we'll embed Bing Crosby's "White Christmas":


There is not much need to explain here. Just like you insert an image with the img tag, you can insert a sound with the tag audio.

Cross browser support

The above example is unlikely to work in all browsers. The issue here is the file format.

Some browsers can play .mp3 files but not .ogg files, while others do the opposite. Most browsers can play .wav files, but due to its large size, it is inappropriate to use it as a sound for a website.

Here is a table of browsers, which indicates the support for sound formats:

What formats does your browser support? Define it with .

As can be seen in the table, the most optimal implementation would be to connect both file formats.
In order to do this, you can add multiple source elements to the element audio, and specify paths to various formats in them. The browser will play the first file it supports. Here is an example:


Of course, this means that you need to create both an Mp3 and an OGG version of your audio file (this is where ) comes in handy, but that's the only way to get cross-browser support.

Early versions of Internet Explorer (versions 7 and 8) do not support the element at all. audio. However, later in the article we will look at how to get around this ailment.

Automatic sound playback

Although the above code embeds the sound, it does not play it. If we want the sound to play automatically when the page loads, we need to add the autoplay attribute to the element:


Adding Control Buttons

While autoplay can be useful, in many cases it's annoying or inappropriate. Therefore, we can set additional control buttons of elements audio so that the user can decide:


This adds a horizontal bar with a pause/play button, a timeline with a slider, and a volume control. Everything is about the same as you can see on the player in Youtube.

It is important to remember that the control panel will differ depending on the browsers. For example, the browser on the iPhone will not have a volume slider, since the device has separate buttons for controlling the volume level.

Looped playback

Adding a loop attribute to the audio element will make the sound play indefinitely.


This can be useful for turning on background music or sound effects in games.

You can also use the preload attribute, which will tell the browser when and where a particular sound file should be loaded.
Preloading the sound file means that the sound can be played immediately when the user presses the play button.

There are several values ​​for this attribute:

« none' - the browser should not impose the downloaded file. Those. if you are sure that most users will not play this file, use this option. Or use it when you need to conserve as much server bandwidth as possible.

« metadata' is similar to none, except that you notify the browser that metadata can be loaded, such as the duration of the audio track, but not the audio file itself.

« auto" - you allow the browser to download the audio file itself.

For example:


Keep in mind that prefetching is just a handy addition, as some browsers might just ignore this command and do whatever they want.

Playback control via javascript

What's nice about javascript elements is that they're easy to manipulate with javascript. The audio element offers many convenient options and control methods:

Play()– start playback from the current position;

Pause()– stop playback at the current position;

canPlayType(type)– determine whether the browser supports playback of this media type;

duration– duration of the track in seconds;

currentTime– current position in seconds. You can also set this parameter to move the playback position.

Using the options and methods suggested above, we can create some basic control buttons:




View demo: http://www.elated.com/res/File/articles/authoring/html/html5-audio/javascript-control.html

Support for earlier versions of Internet Explorer

In most cases, the user's browser will support the HTML5 element. But, unfortunately, IE versions 7 and even 8 do not support this element (although IE 9 already does). It's important to think about the rollback version for users who stayed in 2008.

A very crude but effective method is to use special comments to highlight browser data, and give it an object pointer before the sound file. As such, the browser will often display an inline controller that allows users to play, pause, or rewind music in an almost HTML5 audio-like fashion. Here is an example:






Вышеприведенный пример будет работать во всех браузерах, которые поддерживают HTML5 Audio, и также будет работать в браузерах IE версий 7 и 8. С помощью комментариев, мы перенаправляем рычаги управления для кнопок напрямую к звуковому файлу.

Другой способ отката заключается во внедрении в страницу Flash-плеера. Вот , в которой говорится об откате в виде плеера на Flash.

Заключение

В нашей сегодняшней статье мы научились встраивать аудио-файлы посредством HTML5. Элемент audio не только прост в использовании, но мы также можем оформить его под собственные требования, а также управлять воспроизведением посредством javascript.

Хотите узнать больше об элементе audio в HTML5? Тогда ознакомьтесь со .

Хотя пока что поддержка страдает в некоторых браузерах (типа старых версий IE), можно без проблем делать откаты для них, если это понадобится, что в наши дни встречается всё реже и реже.

andew

2015-08-10T19:23:37+00:00

2016-02-28T17:11:05+00:00

11937

В статье описаны строение audio и video контейнера HTML5, теги video, audio, source, track и их атрибуты с возможными значениями. Приведены HTML шаблоны и примеры реализации воспроизведения мультимедийных файлов на основе встроенных в браузер возможностей. Показано подключение к видео текстовой дорожки субтитров, заголовков, оглавления при помощи файлов формата WEBVTT с примерами. Представлены HTML5 шаблоны кода с микроразметкой по schema.org для аудио и видео. Указаны основные для web форматы аудио и видео файлов с их MIME типами и инструменты для конвертации видео и аудио в эти форматы.

В HTML5 присутствуют новые возможности, позволяющие выполнять проигрывание аудио и видео файлов напрямую браузером без использования сторонних программ. Пока, несмотря на то, что HTML5 уже не новость, имеются еще разногласие в том, как браузеры обрабатывают теги video и audio и как отображают сам плеер. Одни это делают все лучше с каждой новой версией, другие пока еще отстают. Глобально же, тенденция идет к тому, что браузеры будут предоставлять все больше функционала для проигрывания мультимедиа файлов.

Скринкаст: Пример использования шаблонов

Скачать видео

Скринкаст : примеры использования шаблонов из статьи - сайт

HTML5 видео и аудио развивающийся стандарт и он не связан ни с одним форматом аудио или видео, поэтому между браузерами существуют различия в поддерживаемых ими форматами аудио и видео файлов. Это различие сейчас компенсируют тем, что кодируют оригинальный файл несколькими разными кодеками и подключают все эти версии файлов к тегам или через вложенные теги < source src=" URL"> . Однако среди поддерживаемых браузерами форматов аудио и видео файлов намечаются лидеры. Для видео это, конечно же, формат mp4 (H.264 ), и для аудио это формат mp3 и m4a . Сейчас уже, наверное, все браузеры способны проигрывать файлы этих форматов. Так же, браузеры Firefox , Chrome и Opera договорились поддерживать стандарт WEBM в качестве общего видео формата. С моей точки зрения, оптимальным на сейчас вариантом использования HTML5 видео и аудио будет схема основанная на использовании одного мультимедийного файла в формате mp4 (H.264 ) для видео и m4a для аудио и JS HTML5 плеера. К аудио или видео контейнеру подключается только один файл в указанном формате. Сейчас большинство браузеров способны воспроизводить mp4 формат. Подключенная же JS библиотека выполнит стилизацию встроенного в браузер плеера. Если браузер не будет поддерживать формат mp4 /m4a , то JS плеер, в таком случае, реализует подключение Flash плеера для воспроизведения мультимедийного файла. Учитывая, что mp4 формат стал сильно популярен, можно надеяться на низкую вероятность проблем с его воспроизведением в браузерах. Такая схема требует наличие всего одного мультимедийного файла в указанном формате, что экономит место на диске и ресурсы для обработки файлов. Также, такая схема будет стратегически более правильной, так как тенденция идет к тому, что браузеры все больше и лучше выполняют реализацию HTML5 видео и аудио.

Для указания HTML5 плееру проигрываемого файла нужно, помимо URL файла, передать и MIME тип файла, что бы браузер понимал какой кодек ему нужно использовать. Ниже в таблице привожу наиболее распространенные форматы файлов и их MIME типы.

Форматы файлов и их MIME типы

Файлы мультимедиа Расширения Mime тип
Аудио mp3 mp3 audio/mpeg
Аудио mp4 m4a audio/mp4
Аудио webm webm audio/webm
Аудио ogg ogg audio/ogg
Видео mp4 (H.264) mp4 video/mp4
Видео webm webm video/webm
Видео ogg ogv video/ogg

Инструменты кодирования аудио и видео файлов

Для кодирования видео и аудио файлов в приведенные выше web форматы можно воспользоваться открытой программой , которая поддерживает конвертацию аудио и видео файлов в основные распространенные для веба форматы (MP4 , WebM , Ogg Theora , MP3 и т.п. ). Miro Video Converter доступен для разных операционных систем - Windows , Mac и Linux и является графической оболочкой для консольных утилит и , которые удобно использовать на web сервере для обработки загружаемого видео и аудио в автоматическом режиме.

HTML5 код примера audio с микроразметкой schema.org:

Заголовок аудио

This is how the markup data extracted from the code for the audio template described above will look like.

Audioobject itemType = http://schema.org/AudioObject name = Audio title description = Audio description... isfamilyfriendly = true encodingformat = mp3 duration = PT04M59S uploaddate = 2015-12-31 image = Full URL to image.jpg alternatename = Alternate audio title contenturl href = URL to file.mp3 text = Download audio author person itemType = http://schema.org/Person url href = URL text = Author name name = Author name image = Full url to person.jpg

Minimum audio markup by schema.org should include itemprop="name" , itemprop="description" , itemprop="contentUrl" . The rest of the properties are optional.

An example of the standard use of the HTML5 tag

In the demo, I applied for the tag via attribute class css styles that make the width of the video area dynamic depending on the screen size. The height of the player adjust itself. Try resizing your browser window to see how it works. Therefore, there are no attributes in the code source of this demo width and height for tag , they are replaced css styles. But in the template code listing, this accept is not shown, because is already private.

HTML5 video example code with schema.org micro-markup:

Video Title

Watch on YouTube

Short description for video...">

This is how the microdata data extracted from the code for the video template described above will look like.

Videoobject itemType = http://schema.org/VideoObject name = Video title thumbnail imageobject itemType = http://schema.org/ImageObject contenturl = URL to video-thumbnail.jpg|png width = 100 height = 100 duration = PT14M59S isfamilyfriendly = true uploaddate = 2015-12-31 description = Short description for video... url href = URL to file.mp4 text = Video title author person itemType = http://schema.org/Person url href = URL to author web page text = author name name = author name image = Full URL to author.jpg thumbnailurl = URL to file.jpg|png

Minimum necessary for search engines video markup by schema.org must include all the properties shown in the example code itemprop except for the block itemprop="author" , which is optional for search engines and can be removed if there is no data to fill it. For video-thumbnail Yandex requires specifying microdata according to schema.org as itemprop="thumbnail" as ImageObject, a Google requires you to specify how itemprop="thumbnailUrl" , so you have to paste video-thumbnail file twice, and so the second tag img got style display: none, which would not be displayed in the browser. Can instead of using img tag with display:none pass this property with a tag link via attribute href. Also, despite the fact that microdata can be passed through meta tags that are not shown to the user and link, it is still recommended, if possible, to add micro-markup mainly to tags that will be displayed to the user. Micro markup validation schema.org can be done at these links:,. The main advantage of using microdata is the convenience of such content for search robots and social network robots. These robots extract labeled data and aggregate it. Therefore, the use of microdata improves SEO site and facilitates the automatic dissemination of data in social networks. Detailed description schema markup Schema.org for videos marked up with a schema VideoObjec t on site. Also, it is worth noting that for cases when you embed video on your site not directly, but using video hosting widgets Yandex.Video or YouTube, then you can add your own HTML code block with a description of the video under the widget code block and embed micro-markup into it Schema.org for this video. At the same time, as the URL parameter - links to the video, specify not a direct link to a static file, but set the link received from the video hosting. Although the Schema.org specification says that the link should be to a direct file, search engines also process links to videos from video hosting ( see examples on the Yandex website in the Webmaster section), despite the fact that you cannot download the file from such a link and you cannot view it directly in your HTML5 media player on the page, only in the video hosting widget.

If you are faced with the question from which hosting to upload multimedia audio and video files, then look at the article, which describes the option of inserting media files on a WEB page from Yandex Disk.

Attributes and tags:

Attributes src, preload, autoplay, media group, loop, muted, controls are common attributes for all media elements, including tags and .

autoplay attribute:


Top