В этом уроке я собираюсь познакомить вас с аудио в HTML5 и показать, как создать собственный плеер.
Если вы хотите быстрее, взгляните на готовый HTML5 Audio Player, доступный на Envato Market. Он позволяет создавать списки воспроизведения из самых разных источников и поставляется с огромным набором параметров настройки.
Вы найдёте множество HTML5 experts в Envato Studio, чтобы помочь вам.
Введение
До сих пор внедрение аудио в веб-проект было утомительным процессом, в значительной степени зависящим от сторонних плагинов, вроде Flash. После пресловутого отказа iPhone от плагина и новости о том, что Adobe больше не поддерживает Flash для мобильных устройств, многие разработчики ищут другие способы включения аудио в свои проекты. Именно здесь вступает в действие HTML5 audio, чтобы решить проблему.
Хотя HTML5 предоставляет стандарт воспроизведения аудиофайлов в Интернете, он находится в зачаточном состоянии и ещё долго не сможет предоставить то, что есть у других, таких как Flash. Однако в большинстве случаев этого будет достаточно.
Простой Html5 Audio
Самый простой способ внедрить аудио в веб-страницу с использованием HTML5 — использовать новый audio тег. Добавьте его в свой документ HTML5 со следующим кодом:
<audio controls="controls"> <source src="track.ogg" type="audio/ogg" /> <source src="track.mp3" type="audio/mpeg" /> Your browser does not support the audio element. </audio>
Если вы посмотрите на приведенный выше код, вы увидите, что я объявил тег <audio>
и определил атрибут controls, чтобы мы увидели элементы управления проигрывателя по умолчанию.
Вложенные в <audio>у нас есть 2 ‘src’ тега. Один определяет дорожку MP3, а другой определяет формат OGG. Формат OGG особенно нужен, чтобы позволить музыке играть в Firefox из-за проблем с лицензированием. Firefox не поддерживает MP3 без использования плагина. Строка текста Ваш браузер не поддерживает аудио элемент. Позволяет пользователям с неподдерживаемыми браузерами знать, что происходит.
Плейер HTML5 по умолчанию
Html5 Audio атрибуты тега
Помимо поддержки глобальных атрибутов HTML5, тег также поддерживает набор уникальных для себя атрибутов.
- autoplay — для этого можно установить значение «true» или «left blank» «», чтобы определить, должен ли трек автоматически воспроизводиться сразу после загрузки страницы.
- controls — как показано в примере выше, это определяет, должны ли отображаться нативные элементы управления, такие как «play, pause» и т. д.
- loop — это может быть установлено в «loop» и определяет, должен ли трек снова воспроизводиться после его завершения.
- preload — для этого может быть установлен «auto» (описывает, должен ли файл загружаться сразу после загрузки страницы), «metadata» (определяют, должны ли загружаться только метаданные, название дорожки и т. д.), «none» (диктует, что браузер не должен загружать файл при загрузке страницы).
- src — как в примере выше, определяет URL-адрес музыки, которую должен воспроизводить audio tag.
Запустим его на полную (Cranking it up to Eleven)
В последних нескольких шагах мы рассмотрели простейшую форму аудио в формате HTML5. Когда мы начинаем использовать аудио-тег с javascript, мы можем начать создание действительно интересных и полезных аудиоплееров. Давайте посмотрим, что может сделать для нас jQuery. Когда мы определили document ready в jQuery, мы можем создать новую звуковую переменную, чтобы держать наш аудиофайл таким простым:
var myaudio = new Audio('mysong.mp3');
Это действительно настолько просто! Тогда, когда мы хотим выполнить действие над аудио, мы можем вызвать его, используя переменную ‘myaudio’. Вот список действий, которые мы можем предпринять с переменной. Запомните это, мы будем использовать некоторые из них позже, когда создадим наш аудиоплеер.
myaudio.play(); - This will play the music. myaudio.pause(); - This will stop the music. myaudio.duration; - Returns the length of the music track. myaudio.currentTime = 0; - This will rewind the audio to the beginning. myaudio.loop = true; - This will make the audio track loop. myaudio.muted = true; - This will mute the track
Если вы хотите, чтобы функция была вызвана после завершения воспроизведения звука, вы можете использовать ‘myaudio.addEventListener (‘ ended ‘, myfunc)’ — это вызовет функцию ‘myfunc ()’, как только аудио закончится.
Создание HTML5 Audio Player: разметка
Теперь, когда у вас есть немного фона HTML5 и вы понимаете основные принципы, пришло время применить их на практике и создать настроенный HTML5 audio player. Я пропущу этап дизайна, поскольку он выходит за рамки этого урока, но вы можете загрузить accompanying source code и просмотреть PSD, чтобы получить представление о том, как он собирается.
Верхняя часть документа состоит из HTML5 doctype. Yahoos CSS Reset, Google web font ‘Lobster’ для титула. Берём последний jQuery и делаем JavaScript file js.js. Наконец, у нас есть html5 slider.js, который позволяет Firefox отображать диапазон ввода HTML5, который мы будем использовать для аудио scrubber.
<!DOCTYPE html> <head> <title>HTML5 Audio Tutorial</title> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css"> <link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="css/style.css"> <script src="http://code.jQuery.com/jQuery-latest.js" type="text/javascript"></script> <script type="text/javascript" src="js/js.js"></script> <script type="text/javascript" src="js/html5slider.js"></script> </head>
После названия h1 я создал div с классом «container» и «gradient». Я создал отдельный класс градиента, поскольку он будет повторно использоваться для некоторых других элементов. Внутри «.container» я добавил изображение (которое будет обложкой альбома), тогда три якорных тега будут действовать как элементы управления для проигрывателя. Между ними вы найдете поле ввода scubber/HTML5 range.
<body> <h1>HTML 5 Audio Player</h1> <div class="container gradient"> <img class="cover" src="images/cover.jpg" alt=""> <div class="player gradient"> <a class="button gradient" id="play" href="" title=""></a> <a class="button gradient" id="mute" href="" title=""></a> <input type="range" id="seek" value="0" max=""/> <a class="button gradient" id="close" href="" title=""></a> </div><!-- / player --> </div><!-- / Container--> </body> </html>
Создание HTML5 Audio Player: стили
Вместо того, чтобы перебирать каждый аспект CSS, я собираюсь дать обзор и обратить внимание на отдельные части, на которые вы, возможно, захотите обратить внимание.
В коде ниже я создал градиент плеера, который был сгенерирован с помощью этого CSS gradient editor. Затем я создал «.container» с некоторыми переходами CSS3.
Вы заметите, что я использовал атрибут размера окна CSS3, установленный в ‘border-box’. Это отступ 10px вокруг контейнера, шириной, в данном случае 427px. Если этого не сделать, добавление padding к 427px сделало бы контейнер больше, чем мне надо. В наши дни становится обычной практикой применять * {box-sizing: border-box;}
, что фактически делает более интуитивно понятным способ стилизации.
Я также добавил CSS3-переходы в «.coverlarge», чтобы позволить некоторые приятные переходы при первом открытии проигрывателя. Сначала CSS может показаться немного подавляющим, но многое здесь — это префиксы браузера, чтобы убедиться, что аудиоплеер выглядит и работает одинаково в разных браузерах.
.gradient { border: 1px solid black; -webkit-box-shadow: inset 0 1px 0px rgba(255,255,255,.2); -moz-box-shadow: inset 0 1px 0px rgba(255,255,255,.2); box-shadow: inset 0 1px 0px rgba(255,255,255,.2); background: #494949; /* Old browsers */ background: -webkit-linear-gradient(top, #494949 0%, #434242 31%, #393838 55%, #242323 83%, #1b1a1a 100%, #161515 100%, #0b0b0b 100%); background: -moz-linear-gradient(top, #494949 0%, #434242 31%, #393838 55%, #242323 83%, #1b1a1a 100%, #161515 100%, #0b0b0b 100%); background: -o-linear-gradient(top, #494949 0%, #434242 31%, #393838 55%, #242323 83%, #1b1a1a 100%, #161515 100%, #0b0b0b 100%); background: -ms-linear-gradient(top, #494949 0%, #434242 31%, #393838 55%, #242323 83%, #1b1a1a 100%, #161515 100%, #0b0b0b 100%); background: linear-gradient(top, #494949 0%, #434242 31%, #393838 55%, #242323 83%, #1b1a1a 100%, #161515 100%, #0b0b0b 100%); /* W3C */ -image filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#494949', endColorstr='#0b0b0b',GradientType=0 ); /* IE6-9 */ } .container { -webkit-transition: all .7s ease; -moz-transition: all .7s ease; -o-transition: all .7s ease; -ms-transition: all .7s ease; transition: all .7s ease; position: absolute; width: 427px; height: 70px; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; -webkit-box-shadow: 0px 0px 13px rgba(0,0,0,.3),inset 0 1px 0px rgba(255,255,255,.2); -moz-box-shadow: 0px 0px 13px rgba(0,0,0,.3),inset 0 1px 0px rgba(255,255,255,.2); box-shadow: 0px 0px 13px rgba(0,0,0,.3),inset 0 1px 0px rgba(255,255,255,.2); top: 50%; left: 50%; margin: -214px 0px 0px -214px; padding: 10px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; } .containerLarge { height: 427px; } .cover { -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter: alpha(opacity=0); opacity: 0; width: 398px; height: 10px; border: 2px solid black; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: inset 0px 5px 5px rgba(0,0,0,1); -moz-box-shadow: inset 0px 5px 5px rgba(0,0,0,1); box-shadow: inset 0px 5px 5px rgba(0,0,0,1); } .coverLarge { -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter: alpha(opacity=100); opacity: 1; height: 398px; -webkit-transition: opacity .7s ease; -moz-transition: opacity .7s ease; -o-transition: opacity .7s ease; -ms-transition: opacity .7s ease; transition: opacity .7s ease; -webkit-transition-delay: .5s; -moz-transition-delay: .5s; -o-transition-delay: .5s; -ms-transition-delay: .5s; transition-delay: .5s; }
Как аудио плеер должен смотреться на этом этапе
Поскольку контейнер для player завершён, пришло время создать элементы управления. Большинство кнопок были созданы с помощью CSS sprites
К сожалению, IE ещё не поддерживает ввод диапазона HTML5, поэтому я решил не показывать аудио-скруббер пользователям IE. Если для вас это неприемлемо, можете использовать jQuery UI slider аналогично методу, который я использовал. Тем не менее, я просто скрыл скруббер input{display:none9!important;}
Это скрывает ввод от пользователей ie (check out this thread on Stack Overflow дополнительной информации об 9
).
Проблема с ползунком диапазона HTML5 заключается в том, что его поддерживает только несколько браузеров; в основном браузеры WebKit (Chrome и Safari). К сожалению, Opera и Firefox покажут только стандартный слайдер. Если вам нужен пользовательский стиль во всех браузерах, вы можете использовать jQuery UI slider, как упоминалось ранее. Вы видите пользовательский стиль для браузеров WebKit в атрибуте input :: - webkit-slider-thumb
.
.player { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; position: absolute; width: 300px; bottom: 10px; width: 95%; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; padding: 5px; } .button { display: block; width: 34px; height: 34px; background-image: url(../images/sprite.png); background-repeat: no-repeat; float: left; margin-right: 5px; } #play { background-position: 6px 5px; } #pause { background-position: -32px 5px; } #mute { background-position: -63px 5px; } #muted { background-position: -106px 5px; } input[type="range"] { width: 250px; margin-top: -5px; } #close { float: right; background-position: -146px 5px; display: none; } .volume { position: absolute; height: 100px; width: 34px; border: 1px solid black; background-color: #242323; top: -97px; display: none; } input{ display:none9!important; } input[type="range"] { -webkit-appearance: none; border: 1px solid black; position: absolute; top: 18px; display: block; width: 63%; height: 15px; -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; background-color: #242323; left: 90px; -webkit-box-shadow: inset 0px 4px 4px rgba(0,0,0,.6); -moz-box-shadow: inset 0px 4px 4px rgba(0,0,0,.6); box-shadow: inset 0px 4px 4px rgba(0,0,0,.6); } input::-webkit-slider-thumb { -webkit-appearance: none; width: 20px; height: 20px; border:1px solid black; -webkit-border-radius: 10px; border-radius: 10px; background: #80e4df; /* Old browsers */ background: -webkit-linear-gradient(top, #80e4df 0%, #75dbd6 13%, #5ec4bf 33%, #57bbb6 47%, #419d99 80%, #378f8b 100%); background: -moz-linear-gradient(top, #80e4df 0%, #75dbd6 13%, #5ec4bf 33%, #57bbb6 47%, #419d99 80%, #378f8b 100%); background: -o-linear-gradient(top, #80e4df 0%, #75dbd6 13%, #5ec4bf 33%, #57bbb6 47%, #419d99 80%, #378f8b 100%); background: linear-gradient(top, #80e4df 0%, #75dbd6 13%, #5ec4bf 33%, #57bbb6 47%, #419d99 80%, #378f8b 100%); /* W3C */ }
Создание HTML5 Audio Player: jQuery
Поскольку стиль и разметка сделаны, пришло время оживить player. Сделаем это с помощью javascript framework jQuery. Поскольку jQuery document ready
был объявлен, мы создаём некоторые переменные, внутри которых можем хранить наши объекты jQuery.
container = $('.container'); cover = $('.cover'); play = $('#play'); pause = $('#pause'); mute = $('#mute'); muted = $('#muted'); close = $('#close'); song = new Audio('music/track1.ogg','music/track1.mp3'); duration = song.duration;
В приведенной выше переменной «song» вы видите, что мы заявили два трека. Формат OGG для Firefox и MP3 для других браузеров. Затем я создаю условный IF
, чтобы мы могли проверить, может ли браузер воспроизводить MP3. Если да, тогда мы превращаем источник «song» в MP3-трек, если нет, тогда он будет воспроизводиться в формате «OGG».
if (song.canPlayType('audio/mpeg;')) { song.type= 'audio/mpeg'; song.src= 'music/track1.mp3'; } else { song.type= 'audio/ogg'; song.src= 'music/track1.ogg'; }
Следующее, что мы собираемся создать — это функции кликов, которые позволят нам play и pause музыку. Я использую функцию play()
, чтобы запустить звук, а затем метод jQuery replaceWith
, который заменяет кнопку воспроизведения кнопкой паузы.
Я также добавил классы «coverLarge» и «containerLarge» в «container» и «cover». Поскольку я добавил CSS3 переходы ранее в CSS, то появится переход, когда начнётся воспроизведение. Функция «pause» работает аналогично, но без переходов. Нажатие заменяет кнопку pause на кнопку «play».
play.live('click', function(e) { e.preventDefault(); song.play(); $(this).replaceWith('<a class="button gradient" id="pause" href="" title=""></a>'); container.addClass('containerLarge'); cover.addClass('coverLarge'); $('#close').fadeIn(300); $('#seek').attr('max',song.duration); }); pause.live('click', function(e) { e.preventDefault(); song.pause(); $(this).replaceWith('<a class="button gradient" id="play" href="" title=""></a>'); });
Кнопки отключения звука работают аналогично кнопкам воспроизведения и паузы, но вызывают соответствующие действия и заменяют кнопки соответствующими альтернативами.
mute.live('click', function(e) { e.preventDefault(); song.volume = 0; $(this).replaceWith('<a class="button gradient" id="muted" href="" title=""></a>'); }); muted.live('click', function(e) { e.preventDefault(); song.volume = 1; $(this).replaceWith('<a class="button gradient" id="mute" href="" title=""></a>'); });
Когда пользователь нажимает кнопку «close», мы вызываем jQuery для удаления классов «containerLarge» и «coverLarge». Это скроет обложку и закроет плеер. Затем мы приостанавливаем проигрыватель, вызывая действие pause ()
и восстанавливая аудио currentTime на 0. Это возвращает дорожку к началу.
$('#close').click(function(e) { e.preventDefault(); container.removeClass('containerLarge'); cover.removeClass('coverLarge'); song.pause(); song.currentTime = 0; $('#pause').replaceWith('<a class="button gradient" id="play" href="" title=""></a>'); $('#close').fadeOut(300); });
Пришло время перейти на звуковой скруббер, которому присвоен идентификатор «seek». Первая функция позволяет нам переместить скруббер в любую часть аудио. Это делается путем обнаружения изменений, когда кто-либо перемещает скруббер. Затем мы устанавливаем song.currentTime, чтобы он соответствовал части песни, в которую переместился скруббер. Мы также устанавливаем атрибут max, чтобы отражать продолжительность песни.
$("#seek").bind("change", function() { song.currentTime = $(this).val(); $("#seek").attr("max", song.duration); });
Заключительная часть jQuery состоит в том, чтобы заставить скруббер «#seek» двигаться вместе с продолжительностью звука. Мы добавим к нему прослушиватель событий, а при обновлении звукового времени вызываем функцию. Я установил переменную «curtime», чтобы получить текущее время песни. Затем я обновляю значение скруббера, чтобы отобразить текущую временную позицию аудио.
song.addEventListener('timeupdate',function (){ curtime = parseInt(song.currentTime, 10); $("#seek").attr("value", curtime); });
И вот оно! Аудиоплеер HTML5, который вы можете внедрить на своем сайте или в приложении.
Заключение
Как упоминалось ранее, аудио HTML5 находится в зачаточном состоянии и требует усовершенствований. На данный момент аудио передаётся с сервера, поэтому некоторые браузеры имеют проблемы с воспроизведением. Это не всегда проблема, просто означает, что иногда начнёт воспроизведение до того, как аудио полностью загрузится.
Это может быть проблемой, если вы хотите использовать аудио HTML5 для таких вещей, как звуковые эффекты в играх или приложения с интенсивным звуком. По этой причине наши друзья из Google разработали метод улучшения слабых мест аудиотеки. Компания Google разработала и представила предложение к W3C для «Web Audio API». Это оказывается намного более мощным, чем встроенный звук HTML5, однако проблема в том, что на этом этапе (вы можете догадаться ?!) он работает только в Chrome.
Вы можете узнать больше об API Web Audio Google, а также ознакомиться с примерами в Google code или с web audio specification.
Надеюсь, вам понравился урок об аудио HTML5 и о том, как можно создать собственный плеер. Мой player включает в себя элементарные элементы управления, но вам ничто не мешает добавить функции, такие как управление громкостью и даже добавление собственных пользовательских анимаций. Если немного подумать и попробовать, вы действительно можете создать отличные аудиоплееры. Download the source code, я с нетерпением жду того, что вы придумали!
Если вы хотите увидеть больше возможностей для работы с аудиоплеерами и другими медиафайлами в HTML5, ознакомьтесь с материалами HTML5 Media на Envato Market.
Какие темы затрагиваются:
- Установка аудиоплеера в веб-страницу
- Стилизация аудиоплеера с использованием css
- Настройка аудиоплеера (с дополнительными возможностями) с использованием javascript
Можно ли использовать стили для audio тэга (стандартного плеера)?
Как написано в MDN Web Docs:
You can style the default controls with properties that affect the block as a single unit…You can’t however style the individual components inside the audio player (e.g. change the button size or icons, change the font, etc.)…
Это означает, что недостаточно использовать только стандартную аудиорепрезентацию, если вы преследуете такие цели:
- изменять форму и цвет элементов плеера (пуск, пауза и т.д.)
- добавлять кастомные элементы плеера
- использовать анимации и другие способи стилизации для внутренних элементов плеера
Как создать кастомный аудиоплеер?
Кастомный аудіоплеер состоит из двух функциональных частей:
- Html структура с элементами контроля и использования специфических возможностей audio. Html темплейт необходимого плеера.
- Javascript функции для отслеживания событий элементов контроля и использования функционала стандартного (дефолтного) аудиоплеера через HTMLMediaElement Api.
Стандартный аудиоплеер
<audio controls> <source src="/audio.mp3" type="audio/mp3"> Your browser does not support the audio element. </audio>
Your browser does not support the audio element.
Html темплейт кастомного плеера
По сути кастомный темплейт использует стандартный плеер в основе, но не показывает его.
<div class="player"> <audio id="av-tag" controls><source src="/audio.mp3" type="audio/mp3"> Your browser does not support the audio element. </audio> <button class="play-btn">►</button> <div class="play-time">1:00</div> <input id="cur-time" type="range" min="0" max="10" step="0"> <div id="speaker">🔊</div> <input id="volume" type="range" min="0" max="10"> </div>
Your browser does not support the audio element.
1:00
🔊
Javascript HTMLMediaElement Api
document.addEventListener("DOMContentLoaded", (e)=> { //dom объекты элементов контроля var av = document.getElementById("av-tag"); var playTime = document.getElementsByClassName("play-time")[0]; var playBtn=document.getElementsByClassName("play-btn")[0]; var curTime=document.getElementById("cur-time"); var volume = document.getElementById("volume"); var speaker=document.getElementById("speaker"); //переменная для отслеживания воспроизведения звука var isPlaying = false; av.onloadedmetadata = function() { curTime.max=av.duration; }; //функция вывода текущего времени воспроизведения av.ontimeupdate=function() { var sec_num = av.currentTime; var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); seconds=Math.round(seconds); if (hours < 10) { hours = "0"+hours; } if (minutes < 10) { minutes = "0"+minutes; } if (seconds < 10) { seconds = "0"+seconds; } playTime.innerHTML = minutes+':'+seconds; if(isPlaying) curTime.value=av.currentTime; }; //функция для настройки громкости volume.onchange=function() { av.volume = volume.value/10; }; //функция для установки начала воспроизведения curTime.onchange=function() { av.pause(); av.currentTime=curTime.value; av.play(); }; //функция для вкл/выкл громкости speaker.onclick=function() { if(volume.value==0) { volume.value=10; av.volume=1; } else { volume.value=0; av.volume=0; } }; //функция для play/pause и изображения кнопки воспроизведения playBtn.addEventListener("click", (a)=> { if(isPlaying) { av.pause(); isPlaying=false; playBtn.innerHTML="►"; } else { av.play(); isPlaying=true; playBtn.innerHTML="❚❚"; } }); });
CSS стили для аудиоплеера
.player * { display: inline-block; vertical-align: middle; background: none; border: none; font-size: x-large; } .player audio { display: none; } .player { border: 2px solid #600a6f; background: #e9defd; width: max-content; padding: 12px; border-radius: 20px; } .player input[type="range"] { -webkit-appearance: none; height: 5px; border-radius: 5px; background: white; outline: none; opacity: 0.7; -webkit-transition: .2s; transition: opacity .2s; } .player input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 10px; height: 10px; border-radius: 50%; background: #4CAF50; cursor: pointer; } .player input[type="range"]::-moz-range-thumb { width: 10px; height: 10px; border-radius: 50%; background: #4CAF50; cursor: pointer; } #volume { width: 40px; }
I haven’t found any resources on how to do that. Something as simple as changing the color of the player would be nice to have
asked Nov 8, 2010 at 18:18
rabidmachine9rabidmachine9
7,69710 gold badges45 silver badges59 bronze badges
4
Yes: you can hide the built-in browser UI (by removing the controls
attribute from audio
) and instead build your own interface and control the playback using Javascript (source):
<audio id="player" src="vincent.mp3"></audio>
<div>
<button onclick="document.getElementById('player').play()">Play</button>
<button onclick="document.getElementById('player').pause()">Pause</button>
<button onclick="document.getElementById('player').volume += 0.1">Vol +</button>
<button onclick="document.getElementById('player').volume -= 0.1">Vol -</button>
</div>
You can then style the elements however you wish using CSS.
MDN HTMLAudioElement API reference
answered Oct 6, 2016 at 15:17
3
<audio>
audio::-webkit-media-controls-panel
audio::-webkit-media-controls-mute-button
audio::-webkit-media-controls-play-button
audio::-webkit-media-controls-timeline-container
audio::-webkit-media-controls-current-time-display
audio::-webkit-media-controls-time-remaining-display
audio::-webkit-media-controls-timeline
audio::-webkit-media-controls-volume-slider-container
audio::-webkit-media-controls-volume-slider
audio::-webkit-media-controls-seek-back-button
audio::-webkit-media-controls-seek-forward-button
audio::-webkit-media-controls-fullscreen-button
audio::-webkit-media-controls-rewind-button
audio::-webkit-media-controls-return-to-realtime-button
audio::-webkit-media-controls-toggle-closed-captions-button
REFERENCE: https://chromium.googlesource.com/chromium/blink/+/72fef91ac1ef679207f51def8133b336a6f6588f/Source/core/css/mediaControls.css?autodive=0%2F%2F%2F
answered Nov 26, 2015 at 23:11
8
Yes! The HTML5 audio tag with the «controls» attribute uses the browser’s default player. You can customize it to your liking by not using the browser controls, but rolling your own controls and talking to the audio API via javascript.
Luckily, other people have already done this. My favorite player right now is jPlayer, it is very stylable and works great. Check it out.
answered Nov 8, 2010 at 18:38
BennyBenny
1,2482 gold badges12 silver badges21 bronze badges
8
some color tunings
audio {
filter: sepia(20%) saturate(70%) grayscale(1) contrast(99%) invert(12%);
width: 200px;
height: 25px;
}
answered Feb 18, 2019 at 10:02
2
The appearance of the tag is browser-dependent, but you can hide it, build your own interface and control the playback using Javascript.
answered Nov 8, 2010 at 18:20
MihaiMihai
2,7751 gold badge27 silver badges36 bronze badges
Ken had it right as well.
a css
tag:
audio {
}
will get you some results. seems it doesnt want the player any height above or below 25px but the width can be shortened or lengthened to an extent.
this was good enough for me; see this example (warning, audio plays automatically): www.thenewyorkerdeliinc.com
answered May 30, 2012 at 15:08
NickNick
911 silver badge1 bronze badge
3
Missing the most important one IMO the container for the controls ::-webkit-media-controls-enclosure
:
&::-webkit-media-controls-enclosure {
border-radius: 5px;
background-color: green;
}
answered Oct 8, 2020 at 17:29
StefanBobStefanBob
4,7522 gold badges31 silver badges38 bronze badges
Yes, it’s possible, from @Fábio Zangirolami answer
audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
background-color: red;
}
answered Apr 2, 2020 at 12:20
Hernán EcheHernán Eche
6,32412 gold badges53 silver badges75 bronze badges
0
To change just the colour of the player, simply address the audio tag in your css file, for instance on one of my sites the player became invisible (white on white) so I added:
audio {
background-color: #95B9C7;
}
This changed the player to light blue.
answered May 23, 2011 at 17:41
KarinKarin
1471 silver badge2 bronze badges
3
If you are using Chrome, turned on «Show user agent shadow DOM» in Chrome Dev Tool settings
Now you’ll able to see all the pseudos
audio::-webkit-media-controls-panel
audio::-webkit-media-controls-mute-button
audio::-webkit-media-controls-play-button
...
and now you can style them
audio::-webkit-media-controls-mute-button {
display: none;
}
answered Apr 17, 2022 at 4:03
Alex GAlex G
1,2411 gold badge22 silver badges31 bronze badges
I did some customizations on the Audio component. Here is what i did.
audio {
/*border-radius: 90px;*/
width: 250px;
height: 45px;
margin-top: 5px;
margin-bottom: 5px;
}
audio::-webkit-media-controls-mute-button {
display: none !important;
}
audio::-webkit-media-controls-volume-slider {
display: none !important;
}
audio::-webkit-media-controls-volume-control-container.closed {
display: none !important;
}
audio::-webkit-media-controls-volume-control-container{
display: none !important;
}
I found that these customizations only works for Edge and Chrome. Not Firefox..
answered May 18, 2021 at 21:17
You can use HTMLMediaElement Api to create your own audioplayer with html/css. It is likely the only option. Because the default player can’t be styled.
answered Sep 11, 2021 at 22:41
If you want to style the browsers standard music player in the CSS:
audio {
enter code here;
}
adrianbanks
80.4k22 gold badges177 silver badges204 bronze badges
answered Dec 23, 2011 at 15:47
2
DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!
HTML has a built-in native audio player interface that we get simply using the <audio>
element. Point it to a sound file and that’s all there is to it. We even get to specify multiple files for better browser support, as well as a little CSS flexibility to style things up, like giving the audio player a border, some rounded corners, and maybe a little padding and margin.
But even with all that… the rendered audio player itself can look a little, you know, plain.
Did you know it’s possible to create a custom audio player? Of course we can! While the default <audio>
player is great in many cases, having a custom player might suit you better, like if you run a podcast and an audio player is the key element on a website for the podcast. Check out the sweet custom player Chris and Dave set up over at the ShopTalk Show website.
We’re going to take stab at making our own player in this post. So, put on your headphones, crank up some music, and let’s get to work!
The elements of an audio player
First, let’s examine the default HTML audio players that some of the popular browsers provide.
If our goal is to match the functionality of these examples, then we need to make sure our player has:
- a play/pause button,
- a seek slider,
- the current time indicator,
- the duration of the sound file,
- a way to mute the audio, and
- a volume control slider.
Let’s say this is the design we’re aiming for:
We’re not going for anything too fancy here: just a proof of concept sorta thing that we can use to demonstrate how to make something different than what default HTML provides.
Basic markup, styling and scripts for each element
We should first go through the semantic HTML elements of the player before we start building features and styling things. We have plenty of elements to work with here based on the elements we just listed above.
Play/pause button
I think the HTML element appropriate for this button is the <button>
element. It will contain the play icon, but the pause icon should also be in this button. That way, we’re toggling between the two rather than taking up space by displaying both at the same time.
Something like this in the markup:
<div id="audio-player-container">
<p>Audio Player</p>
<!-- swaps with pause icon -->
<button id="play-icon"></button>
</div>
So, the question becomes: how do we swap between the two buttons, both visually and functionally? the pause icon will replace the play icon when the play action is triggered. The play button should display when the audio is paused and the pause button should display when the audio is playing.
Of course, a little animation could take place as the icon transitions from the play to pause. What would help us accomplish that is Lottie, a library that renders Adobe After Effects animations natively. We don’t have to create the animation on After Effects though. The animated icon we’re going to use is provided for free by Icons8.
New to Lottie? I wrote up a thorough overview that covers how it works.
In the meantime, permit me to describe the following Pen:
The HTML section contains the following:
- a container for the player,
- text that briefly describes the container, and
- a
<button>
element for the play and pause actions.
The CSS section includes some light styling. The JavaScript is what we need to break down a bit because it’s doing several things:
// imports the Lottie library via Skypack
import lottieWeb from 'https://cdn.skypack.dev/lottie-web';
// variable for the button that will contain both icons
const playIconContainer = document.getElementById('play-icon');
// variable that will store the button’s current state (play or pause)
let state = 'play';
// loads the animation that transitions the play icon into the pause icon into the referenced button, using Lottie’s loadAnimation() method
const animation = lottieWeb.loadAnimation({
container: playIconContainer,
path: 'https://maxst.icons8.com/vue-static/landings/animated-icons/icons/pause/pause.json',
renderer: 'svg',
loop: false,
autoplay: false,
name: "Demo Animation",
});
animation.goToAndStop(14, true);
// adds an event listener to the button so that when it is clicked, the the player toggles between play and pause
playIconContainer.addEventListener('click', () => {
if(state === 'play') {
animation.playSegments([14, 27], true);
state = 'pause';
} else {
animation.playSegments([0, 14], true);
state = 'play';
}
});
Here’s what the script is doing, minus the code:
- It imports the Lottie library via Skypack.
- It references the button that will contain both icons in a variable.
- It defines a variable that will store the button’s current state (play or pause).
- It loads the animation that transitions the play icon into the pause icon into the referenced button, using Lottie’s
loadAnimation()
method. - It displays the play icon on load since the audio is initially paused.
- It adds an event listener to the button so that when it is clicked, the the player toggles between play and pause.
Current time and duration
The current time is like a progress indicate that shows you how much time has elapsed from the start of the audio file. The duration? That’s just how long the sound file is.
A <span>
element is okay to display these. The <span>
element for the current time, which is to be updated every second, has a default text content of 0:00
. On the other side, the one for duration is the duration of the audio in mm:ss
format.
<div id="audio-player-container">
<p>Audio Player</p>
<button id="play-icon"></button>
<span id="current-time" class="time">0:00</span>
<span id="duration" class="time">0:00</span>
</div>
Seek slider and volume control slider
We need a way to move to any point in time in the sound file. So, if I want to skip ahead to the halfway point of the file, I can simply click and drag a slider to that spot in the timeline.
We also need a way to control the sound volume. That, too, can be some sort of click-and-drag slider thingy.
I would say <input type="range">
is the right HTML element for both of these features.
<div id="audio-player-container">
<p>Audio Player</p>
<button id="play-icon"></button>
<span id="current-time" class="time">0:00</span>
<input type="range" id="seek-slider" max="100" value="0">
<span id="duration" class="time">0:00</span>
<input type="range" id="volume-slider" max="100" value="100">
</div>
Styling range inputs with CSS is totally possible, but I’ll tell you what: it is difficult for me to wrap my head around. This article will help. Mad respect to you, Ana. Handling browser support with all of those vendor prefixes is a CSS trick in and of itself. Look at all the code needed on input[type="range"]
to get a consistent experience:
input[type="range"] {
position: relative;
-webkit-appearance: none;
width: 48%;
margin: 0;
padding: 0;
height: 19px;
margin: 30px 2.5% 20px 2.5%;
float: left;
outline: none;
}
input[type="range"]::-webkit-slider-runnable-track {
width: 100%;
height: 3px;
cursor: pointer;
background: linear-gradient(to right, rgba(0, 125, 181, 0.6) var(--buffered-width), rgba(0, 125, 181, 0.2) var(--buffered-width));
}
input[type="range"]::before {
position: absolute;
content: "";
top: 8px;
left: 0;
width: var(--seek-before-width);
height: 3px;
background-color: #007db5;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
position: relative;
-webkit-appearance: none;
box-sizing: content-box;
border: 1px solid #007db5;
height: 15px;
width: 15px;
border-radius: 50%;
background-color: #fff;
cursor: pointer;
margin: -7px 0 0 0;
}
input[type="range"]:active::-webkit-slider-thumb {
transform: scale(1.2);
background: #007db5;
}
input[type="range"]::-moz-range-track {
width: 100%;
height: 3px;
cursor: pointer;
background: linear-gradient(to right, rgba(0, 125, 181, 0.6) var(--buffered-width), rgba(0, 125, 181, 0.2) var(--buffered-width));
}
input[type="range"]::-moz-range-progress {
background-color: #007db5;
}
input[type="range"]::-moz-focus-outer {
border: 0;
}
input[type="range"]::-moz-range-thumb {
box-sizing: content-box;
border: 1px solid #007db5;
height: 15px;
width: 15px;
border-radius: 50%;
background-color: #fff;
cursor: pointer;
}
input[type="range"]:active::-moz-range-thumb {
transform: scale(1.2);
background: #007db5;
}
input[type="range"]::-ms-track {
width: 100%;
height: 3px;
cursor: pointer;
background: transparent;
border: solid transparent;
color: transparent;
}
input[type="range"]::-ms-fill-lower {
background-color: #007db5;
}
input[type="range"]::-ms-fill-upper {
background: linear-gradient(to right, rgba(0, 125, 181, 0.6) var(--buffered-width), rgba(0, 125, 181, 0.2) var(--buffered-width));
}
input[type="range"]::-ms-thumb {
box-sizing: content-box;
border: 1px solid #007db5;
height: 15px;
width: 15px;
border-radius: 50%;
background-color: #fff;
cursor: pointer;
}
input[type="range"]:active::-ms-thumb {
transform: scale(1.2);
background: #007db5;
}
Whoa! What does even mean, right?
Styling the progress section of range inputs is a tricky endeavor. Firefox provides the ::-moz-range-progress
pseudo-element while Internet Explorer provides ::-ms-fill-lower
. As WebKit browsers do not provide any similar pseudo-element, we have to use the ::before
pseudo-element to improvise the progress. That explains why, if you noticed, I added event listeners in the JavaScript section to set custom CSS properties (e.g. --before-width
) that update when the input event is fired on each of the sliders.
One of the native HTML <audio>
examples we looked at earlier shows the buffered amount of the audio. The --buffered-width
property specifies the amount of the audio, in percentage, that the user can play through to without having to wait for the browser to download. I imitated this feature with the linear-gradient()
function on the track of the seek slider. I used the rgba()
function in the linear-gradient()
function for the color stops to show transparency. The buffered width has a much deeper color compared to the rest of the track. However, we would treat the actual implementation of this feature much later.
Volume percentage
This is to display the percentage volume. The text content of this element is updated as the user changes the volume through the slider. Since it is based on user input, I think this element should be the <output>
element.
<div id="audio-player-container">
<p>Audio Player</p>
<button id="play-icon"></button>
<span id="current-time" class="time">0:00</span>
<input type="range" id="seek-slider" max="100" value="0">
<span id="duration" class="time">0:00</span>
<output id="volume-output">100</output>
<input type="range" id="volume-slider" max="100" value="100">
</div>
Mute button
Like for the play and pause actions, this should be in a <button>
element. Luckily for us, Icons8 also has an animated mute icon. So we would use the Lottie library here just as we did for the play/pause button.
<div id="audio-player-container">
<p>Audio Player</p>
<button id="play-icon"></button>
<span id="current-time" class="time">0:00</span>
<input type="range" id="seek-slider" max="100" value="0">
<span id="duration" class="time">0:00</span>
<output id="volume-output">100</output>
<input type="range" id="volume-slider" max="100" value="100">
<button id="mute-icon"></button>
</div>
That’s all of the basic markup, styling and scripting we need at the moment!
Working on the functionality
The HTML <audio>
element has a preload
attribute. This attribute gives the browser instructions for how to load the audio file. It accepts one of three values:
none
– indicates that the browser should not load the audio at all (unless the user initiates the play action)metadata
– indicates that only the metadata (like length) of the audio should be loadedauto
– loads the complete audio file
An empty string is equivalent to the auto
value. Note, however, that these values are merely hints to the browser. The browser does not have to agree to these values. For example, if a user is on a cellular network on iOS, Safari does not load any part of an audio, regardless of the preload
attribute, except the user triggers the play action. For this player, we would use the metadata
value since it doesn’t require much overhead and we want to display the length of the audio.
What would help us accomplish the features our audio player should have is the JavaScript HTMLMediaElement
interface, which the HTMLAudioElement
interface inherits. For our audio player code to be as self-explanatory as possible, I’d divide the JavaScript into two sections: presentation and functionality.
First off, we should create an <audio>
element in the audio player that has the basic features we want:
<div id=”audio-player-container”>
<audio src=”my-favourite-song.mp3” preload=”metadata” loop>
<button id="play-icon"></button>
<!-- ... -->
</div>
Display the audio duration
The first thing we want to display on the browser is the duration of the audio, when it is available. The HTMLAudioElement
interface has a duration
property, which returns the duration of the audio, returned in seconds units. If it is unavailable, it returns NaN
.
We’ve set preload
to metadata
in this example, so the browser should provide us that information up front on load… assuming it respects preload
. Since we’d be certain that the duration will be available when the browser has downloaded the metadata of the audio, we display it in our handler for the loadedmetadata
event, which the interface also provides:
const audio = document.querySelector('audio');
audio.addEventListener('loadedmetadata', () => {
displayAudioDuration(audio.duration);
});
That’s great but, again, we get the duration in second. We probably should convert that to a mm:ss
format:
const calculateTime = (secs) => {
const minutes = Math.floor(secs / 60);
const seconds = Math.floor(secs % 60);
const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
return `${minutes}:${returnedSeconds}`;
}
We’re using Math.floor()
because the seconds returned by the duration
property typically come in decimals.
The third variable, returnedSeconds
, is necessary for situations where the duration is something like 4 minutes and 8 seconds. We would want to return 4:08, not 4:8.
More often than not, the browser loads the audio faster than usual. When this happens, the loadedmetadata
event is fired before its listener can be added to the <audio>
element. Therefore, the audio duration is not displayed on the browser. Nevertheless, there’s a hack. The HTMLMediaElement
has a property called readyState
. It returns a number that, according to MDN Web Docs, indicates the readiness state of the media. The following describes the values:
0
– no data about the media is available.1
– the metadata attributes of the media are available.2
– data is available, but not enough to play more than a frame.3
– data is available, but for a little amount of frames from the current playback position.4
– data is available, such that the media can be played through to the end without interruption.
We want to focus on the metadata. So our approach is to display the duration if the metadata of the audio is available. If it is not available, we add the event listener. That way, the duration is always displayed.
const audio = document.querySelector('audio');
const durationContainer = document.getElementById('duration');
const calculateTime = (secs) => {
const minutes = Math.floor(secs / 60);
const seconds = Math.floor(secs % 60);
const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
return `${minutes}:${returnedSeconds}`;
}
const displayDuration = () => {
durationContainer.textContent = calculateTime(audio.duration);
}
if (audio.readyState > 0) {
displayDuration();
} else {
audio.addEventListener('loadedmetadata', () => {
displayDuration();
});
}
Seek slider
The default value of the range slider’s max
property is 100. The general idea is that when the audio is playing, the thumb is supposed to be “sliding.” Also, it is supposed to move every second, such that it gets to the end of the slider when the audio ends.
Notwithstanding, if the audio duration is 150 seconds and the value of the slider’s max
property is 100, the thumb will get to the end of the slider before the audio ends. This is why it is necessary to set the value of the slider’s max
property to the audio duration in seconds. This way, the thumb gets to the end of the slider when the audio ends. Recall that this should be when the audio duration is available, when the browser has downloaded the audio metadata, as in the following:
const seekSlider = document.getElementById('seek-slider');
const setSliderMax = () => {
seekSlider.max = Math.floor(audio.duration);
}
if (audio.readyState > 0) {
displayDuration();
setSliderMax();
} else {
audio.addEventListener('loadedmetadata', () => {
displayDuration();
setSliderMax();
});
}
Buffered amount
As the browser downloads the audio, it would be nice for the user to know how much of it they can seek to without delay. The HTMLMediaElement
interface provides the buffered
and seekable
properties. The buffered
property returns a TimeRanges
object, which indicates the chunks of media that the browser has downloaded. According to MDN Web Docs, a TimeRanges
object is a series of non-overlapping ranges of time, with start and stop times. The chunks are usually contiguous, unless the user seeks to another part in the media. The seekable
property returns a TimeRanges
object, which indicates “seekable” parts of the media, irrespective of whether they’ve been downloaded or not.
Recall that the preload="metadata"
attribute is present in our <audio>
element. If, for example the audio duration is 100 seconds, the buffered
property returns a TimeRanges
object similar to the following:
When the audio has started playing, the seekable
property would return a TimeRanges
object similar to the following:
It returns multiple chunks of media because, more often than not, byte-range requests are enabled on the server. What this means is that multiple parts of the media can be downloaded simultaneously. However, we want to display the buffered amount closest to the current playback position. That would be the first chunk (time range 0 to 20). That would be the first and last chunk from the first image. As the audio starts playing, the browser begins to download more chunks. We would want to display the one closest to the current playback position, which would be the current last chunk returned by the buffered property. The following snippet would store in the variable, bufferedAmount
, i.e. the time for the end of the last range in the TimeRanges
object returned by the buffered
property.
const audio = document.querySelector('audio');
const bufferedAmount = audio.buffered.end(audio.buffered.length - 1);
This would be 20 from the 0 to 20 range in the first image. The following snippet stores in the variable, seekableAmount
, the time for the end of the last range in the TimeRanges
object returned by the seekable
property.
const audio = document.querySelector('audio');
const seekableAmount = audio.seekable.end(audio.seekable.length - 1);
Nevertheless, this would be 100 from the 90 to 100 range in the second image, which is the entire audio duration. Note that there are some holes in the TimeRanges
object as the browser only downloads some parts of the audio. What this means is that the entire duration would be displayed to the user as the buffered amount. Meanwhile, some parts in the audio are not available yet. Because this won’t provide the best user experience, the first snippet is what we should use.
As the browser downloads the audio, the user should expect that the buffered amount on the slider increases in width. The HTMLMediaElement
provides an event, the progress event, which fires as the browser loads the media. Of course, I’m thinking what you’re thinking! The buffered amount should be incremented in the handler for the audio’s progress event.
Finally, we should actually display the buffered amount on the seek slider. We do that by setting the property we talked about earlier, --buffered-width
, as a percentage of the value of the slider’s max
property. Yes, in the handler for the progress event too. Also, because of the browser loading the audio faster than usual, we should update the property in the loadedmetadata
event and its preceding conditional block that checks for the readiness state of the audio. The following Pen combines all that we’ve covered so far:
Current time
As the user slides the thumb along the range input, the range value should be reflected in the <span>
element containing the current time of the audio. This tells the user the current playback position of the audio. We do this in the handler of the slider’s input event listener.
If you think the correct event to listen to should be the change event, I beg to differ. Say the user moved the thumb from value 0 to 20. The input event fires at values 1 through to 20. However, the change event will fire only at value 20. If we use the change event, it will not reflect the playback position from values 1 to 19. So, I think the input event is appropriate. Then, in the handler for the event, we pass the slider’s value to the calculateTime()
function we defined earlier.
We created the function to take time in seconds and return it in a mm:ss
format. If you’re thinking, Oh, but the slider’s value is not time in seconds
, let me explain. Actually, it is. Recall that we set the value of the slider’s max
property to the audio duration, when it is available. Let’s say the audio duration is 100 seconds. If the user slides the thumb to the middle of the slider, the slider’s value will be 50. We wouldn’t want 50 to appear in the current time box because it is not in accordance with the mm:ss
format. When we pass 50 to the function, the function returns 0:50 and that would be a better representation of the playback position.
I added the snippet below to our JavaScript.
const currentTimeContainer = document.getElementById('current-time');
seekSlider.addEventListener('input', () => {
currentTimeContainer.textContent = calculateTime(seekSlider.value);
});
To see it in action, you can move the seek slider’s thumb back and forth in the following Pen:
Play/pause
Now we’re going to set the audio to play or pause according to the respective action triggered by the user. If you recall, we created a variable, playState
, to store the state of the button. That variable is what will help us know when to play or pause the audio. If its value is play
and the button is clicked, our script is expected to perform the following actions:
- play the audio
- change the icon from play to pause
- change the
playState
value topause
We already implemented the second and third actions in the handler for the button’s click event. What we need to do is to add the statements to play and pause the audio in the event handler:
playIconContainer.addEventListener('click', () => {
if(playState === 'play') {
audio.play();
playAnimation.playSegments([14, 27], true);
playState = 'pause';
} else {
audio.pause();
playAnimation.playSegments([0, 14], true);
playState = 'play';
}
});
It is possible that the user will want to seek to a specific part in the audio. In that case, we set the value of the audio’s currentTime
property to the seek slider’s value. The slider’s change event will come in handy here. If we use the input event, various parts of the audio will play in a very short amount of time.
Recall our scenario of 1 to 20 values. Now imagine the user slides the thumb from 1 to 20 in, say, two seconds. That’s 20 seconds audio playing in two seconds. It’s like listening to Busta Rhymes on 3× speed. I’d suggest we use the change
event. The audio will only play after the user is done seeking. This is what I’m talking about:
seekSlider.addEventListener('change', () => {
audio.currentTime = seekSlider.value;
});
With that out of the way, something needs to be done while the audio is playing. That is to set the slider’s value to the current time of the audio. Or move the slider’s thumb by one tick every second. Since the audio duration and the slider’s max
value are the same, the thumb gets to the end of the slider when the audio ends. Now the timeupdate
event of the HTMLMediaElement
interface should be the appropriate event for this. This event is fired as the value of the media’s currentTime
property is updated, which is approximately four times in one second. So in the handler for this event, we could set the slider’s value to the audio’s current time. This should work just fine:
audio.addEventListener('timeupdate', () => {
seekSlider.value = Math.floor(audio.currentTime);
});
However, there are some things to take note of here:
- As the audio is playing, and the seek slider’s value is being updated, a user is unable to interact with the slider. If the audio is paused, the slider won’t be able to receive input from the user because it is constantly being updated.
- In the handler, we update the value of the slider but its input event does not fire. This is because the event only fires when a user updates the slider’s value on the browser, and not when it is updated programmatically.
Let’s consider the first issue.
To be able to interact with the slider while the audio is playing, we would have to pause the process of updating it’s value when it receives input. Then, when the slider loses focus, we resume the process. But, we don’t have access to this process. My hack would be to use the requestAnimationFrame()
global method for the process. But this time, we won’t be using the timeupdate
event for this because it still won’t work. The animation would play forever until the audio is paused, and that’s not what we want. Therefore, we use the play/pause button’s click event.
To use the requestAnimationFrame()
method for this feature, we have to accomplish these steps:
- Create a function to keep our “update slider value” statement.
- Initialize a variable in the function that was previously created to store the request ID returned by the function (that will be used to pause the update process).
- Add the statements in the play/pause button click event handler to start and pause the process in the respective blocks.
This is illustrated in the following snippet:
let rAF = null;
const whilePlaying = () => {
seekSlider.value = Math.floor(audio.currentTime);
rAF = requestAnimationFrame(whilePlaying);
}
playIconContainer.addEventListener('click', () => {
if(playState === 'play') {
audio.play();
playAnimation.playSegments([14, 27], true);
requestAnimationFrame(whilePlaying);
playState = 'pause';
} else {
audio.pause();
playAnimation.playSegments([0, 14], true);
cancelAnimationFrame(rAF);
playState = 'play';
}
});
But this doesn’t exactly solve our problem. The process is only paused when the audio is paused. We also need to pause the process, if it is in execution (i.e. if the audio is playing), when the user wants to interact with the slider. Then, after the slider loses focus, if the process was ongoing before (i.e. if the audio was playing), we start the process again. For this, we would use the slider’s input event handler to pause the process. To start the process again, we would use the change
event because it is fired after the user is done sliding the thumb. Here is the implementation:
seekSlider.addEventListener('input', () => {
currentTimeContainer.textContent = calculateTime(seekSlider.value);
if(!audio.paused) {
cancelAnimationFrame(raf);
}
});
seekSlider.addEventListener('change', () => {
audio.currentTime = seekSlider.value;
if(!audio.paused) {
requestAnimationFrame(whilePlaying);
}
});
I was able to come up with something for the second issue. I added the statements in the seek slider’s input event handlers to the whilePlaying()
function. Recall that there are two event listeners for the slider’s input event: one for the presentation, and the other for the functionality. After adding the two statements from the handlers, this is how our whilePlaying()
function looks:
const whilePlaying = () => {
seekSlider.value = Math.floor(audio.currentTime);
currentTimeContainer.textContent = calculateTime(seekSlider.value);
audioPlayerContainer.style.setProperty('--seek-before-width', `${seekSlider.value / seekSlider.max * 100}%`);
raf = requestAnimationFrame(whilePlaying);
}
Note that the statement on the fourth line is the seek slider’s appropriate statement from the showRangeProgress()
function we created earlier in the presentation section.
Now we’re left with the volume-control functionality. Whew! But before we begin working on that, here’s a Pen covering all we’ve done so far:
Volume-control
For volume-control, we’re utilizing the second slider, #volume-slider
. When the user interacts with the slider, the slider’s value is reflected in the volume of the audio and the <output>
element we created earlier.
The slider’s max
property has a default value of 100. This makes it easy to display its value in the <output>
element when it is updated. We could implement this in the input event handler of the slider. However, to implement this in the volume of the audio, we’re going to have to do some math.
The HTMLMediaElement
interface provides a volume
property, which returns a value between 0 and 1, where 1 being is the loudest value. What this means is if the user sets the slider’s value to 50, we would have to set the volume property to 0.5. Since 0.5 is a hundredth of 50, we could set the volume to a hundredth of the slider’s value.
const volumeSlider = document.getElementById('volume-slider');
const outputContainer = document.getElementById('volume-output');
volumeSlider.addEventListener('input', (e) => {
const value = e.target.value;
outputContainer.textContent = value;
audio.volume = value / 100;
});
Not bad, right?
Muting audio
Next up is the speaker icon, which is clicked to mute and unmute the audio. To mute the audio, we would use its muted
property, which is also available via HTMLMediaElement
as a boolean type. Its default value is false
, which is unmuted. To mute the audio, we set the property to true
. If you recall, we added a click event listener to the speaker icon for the presentation (the Lottie animation). To mute and unmute the audio, we should add the statements to the respective conditional blocks in that handler, as in the following:
const muteIconContainer = document.getElementById('mute-icon');
muteIconContainer.addEventListener('click', () => {
if(muteState === 'unmute') {
muteAnimation.playSegments([0, 15], true);
audio.muted = true;
muteState = 'mute';
} else {
muteAnimation.playSegments([15, 25], true);
audio.muted = false;
muteState = 'unmute';
}
});
Full demo
Here’s the full demo of our custom audio player in all its glory!
But before we call it quits, I’d like to introduce something — something that will give our user access to the media playback outside of the browser tab where our custom audio player lives.
Permit me to introduce to you, drumroll, please…
The Media Session API
Basically, this API lets the user pause, play, and/or perform other media playback actions, but not with our audio player. Depending on the device or the browser, the user initiates these actions through the notification area, media hubs, or any other interface provided by their browser or OS. I have another article just on that for you to get more context on that.
The following Pen contains the implementation of the Media Session API:
If you view this Pen on your mobile, take a sneak peek at the notification area. If you’re on Chrome on your computer, check the media hub. If your smartwatch is paired, I’d suggest you look at it. You could also tell your voice assistant to perform some of the actions on the audio. Ten bucks says it’ll make you smile. 🤓
One more thing…
If you need an audio player on a webpage, there’s a high chance that the page contains other stuff. That’s why I think it’s smart to group the audio player and all the code needed for it into a web component. This way, the webpage possesses a form of separation of concerns. I transferred everything we’ve done into a web component and came up with the following:
Wrapping up, I’d say the possibilities of creating a media player are endless with the HTMLMediaElement
interface. There’s so many various properties and methods for various functions. Then there’s the Media Session API for an enhanced experience.
What’s the saying? With great power comes great responsibility, right? Think of all the various controls, elements, and edge cases we had to consider for what ultimately amounts to a modest custom audio player. Just goes to show that audio players are more than hitting play and pause. Properly speccing out functional requirements will definitely help plan your code in advance and save you lots of time.
HTML5 provides a default video player for rendering video assets. However, with CSS we can tweak and customize the styling of the video player to suit our taste or match our website theme or style.
In this article, I will show you how to customize an HTML5 video player with CSS so that you can create a video player that blends seamlessly into the design of your next app.
In order to follow along in this article, you should have working knowledge of HTML, CSS, and JavaScript, in addition to a working understanding of DOM manipulation and event listening.
I also recommend you use the latest version of your browser or a Chrome browser for best performance.
What is an HTML5 video player?
An HTML5 video player is an HTML5 streaming technology that was created as a more compatible alternative to Adobe Flash Player. It allows a broadcaster to stream video assets over web platforms via an HLS (HTTPS Live Streaming) protocol to fetch content from CDNs (Content Delivery Networks).
All major browsers and operating systems support HTML5 video players.
What does it mean to customize an HTML5 video player?
To customize an HTML5 video player means to change the default look or styling to your taste. This is done by writing a new style sheet for the DOM element that renders a selected video player.
Use cases and real life examples of customized HTML5 video players
You can find real-life examples of customized HTML5 video players on YouTube, the Cloudinary Video Player, JWPlayer, and Video JS. Each of these websites or frameworks utilize the power of CSS to customize their videos or allow their users to do the same.
As you can see, there are many use cases for custom video players, especially in apps where video is the primary function (like YouTube, for example). With the following tutorial, you will learn how to create your own HTML5 video player and customize it to look like a native part of your app.
How create a new HTML5 video player
To create a new HTML5 video player, we will need to create a new project folder. Inside the folder create an HTML file called index.html
.
Type the following code in the index.html
file:
<!DOCTYPE html> <html lang="en"> <body> <video src="https://res.cloudinary.com/codelife/video/upload/v1637805738/intro_l5ul1k.mp4"></video> </body> </html>
In the code above, we have an HTML document with a video
tag in the body. We also passed in a video url as source.
If you preview this webpage in a browser, you should see the following:
In the image above, the HTML5 video player renders a video that we can’t interact with because we have not set the necessary parameters to make the video player functional.
To fix this, let’s go ahead to add more attributes to the video
tag. Replace the video
tag in the HTML document with the following:
<video src="https://res.cloudinary.com/codelife/video/upload/v1637805738/intro_l5ul1k.mp4" controls autoplay loop muted width="400px" height="300px" ></video>
In the code above, we added controls
to display the default controls for the video player. By default it is set to true
(which means controls
is the same as controls="true"
). It only accepts true
or false
as its value.
autoplay
is used to decide whether the video should start playing immediately after it is loaded or not. Every new video element has a default autoplay value of false
until you include autoplay
as an attribute.
loop
is used to decide if a video should start again when it ends. Every new video element has a default loop value of false
.
muted
is used to decide if the video should play with audio or not. Every new video element has a default muted value of false
.
Finally, width
and height
set the horizontal and vertical size of the video.
If you preview the new code in a browser, you should see the following:
Customizing the HTML5 video player
To customize the player we will need to create two additional files: script.js
and style.css
.
Script.js
is where will write the functionality for the video’s controls, while the style.css
is where we will write our stylesheet for the video. We could write the contents of the two files inside index.html
but that would make our code lengthy and untidy.
Replace the content of the index.html
with the following code. This will be the structure of the video before customization:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <div class="container"> <video onclick="play(event)" src="https://res.cloudinary.com/codelife/video/upload/v1637805738/intro_l5ul1k.mp4" id="video"></video> <div class="controls"> <button onclick="play(event)"><i class="fa fa-play"></i><i class="fa fa-pause"></i></button> <button onclick="rewind(event)"><i class="fa fa-fast-backward"></i></button> <div class="timeline"> <div class="bar"> <div class="inner"></div> </div> </div> <button onclick="forward(event)"><i class="fa fa-fast-forward"></i></button> <button onclick="fullScreen(event)"><i class="fa fa-expand"></i></button> <button onclick="download(event)"><i class="fa fa-cloud-download"></i></button> </div> </div> <script src="script.js"></script> </body> </html>
In the above code, we included our custom stylesheet (style.css
) and a Font Awesome CDN link. Then we created a container div, where we included the video and all the controls we added previously.
In the controls div, we have a button that toggles the video playing state, as well as a button to reverse and forward the current time of the video, a button to preview the video in fullscreen, a button to open the video as a downloadable file, and a div to show the current position of the video timeline.
Next, we write our stylesheet. With the stylesheet, we can alter the default styling of the video player by referencing certain objects with the use of selectors, then assign a new attribute to each property we want to customize.
To do that, type the following code inside the style.css
file:
.container { position: relative; display: flex; width: max-content; height: max-content; justify-content: center; align-items: center; } .container #video { width: 600px; height: 400px; border-radius: 20px; } .container .controls { position: absolute; bottom: 40px; width: 100%; display: flex; justify-content: space-around; opacity: 0.2; transition: opacity 0.4s; } .container:hover .controls { opacity: 1; } .container .controls button { background: transparent; color: #fff; font-weight: bolder; text-shadow: 2px 1px 2px #000; border: none; cursor: pointer; } .container .controls .timeline { flex: 1; display: flex; align-items: center; border: none; border-right: 3px solid #ccc; border-left: 3px solid #ccc; } .container .controls .timeline .bar{ background: rgb(1, 1, 65); height: 4px; flex: 1; } .container .controls .timeline .bar .inner{ background: #ccc; width: 0%; height: 100%; } .fa { font-size: 20px !important; }
In this file, you will notice that the container has a position of relative
. This is to control the position of the other elements inside it.
We set the position of the div with the controls
class as position: absolute
and bottom: 40px
. This will place the controls
div 40px from the bottom of the video container. We also specified an !important
font size for our icons.
Next, our video player needs functionality, like a play, pause, and fullscreen button, plus the ability for our users to download, rewind, and forward. These functionalities will make our video player interactive.
Input the following code into script.js
:
// Select the HTML5 video const video = document.querySelector("#video") // set the pause button to display:none by default document.querySelector(".fa-pause").style.display = "none" // update the progress bar video.addEventListener("timeupdate", () => { let curr = (video.currentTime / video.duration) * 100 if(video.ended){ document.querySelector(".fa-play").style.display = "block" document.querySelector(".fa-pause").style.display = "none" } document.querySelector('.inner').style.width = `${curr}%` }) // pause or play the video const play = (e) => { // Condition when to play a video if(video.paused){ document.querySelector(".fa-play").style.display = "none" document.querySelector(".fa-pause").style.display = "block" video.play() } else{ document.querySelector(".fa-play").style.display = "block" document.querySelector(".fa-pause").style.display = "none" video.pause() } } // trigger fullscreen const fullScreen = (e) => { e.preventDefault() video.requestFullscreen() } // download the video const download = (e) => { e.preventDefault() let a = document.createElement('a') a.href = video.src a.target = "_blank" a.download = "" document.body.appendChild(a) a.click() document.body.removeChild(a) } // rewind the current time const rewind = (e) => { video.currentTime = video.currentTime - ((video.duration/100) * 5) } // forward the current time const forward = (e) => { video.currentTime = video.currentTime + ((video.duration/100) * 5) }
In the code snippet above, we created a constant video
which is used to identify the video in the various functions of the script file.
The pause
icon is set to display: none
by default. We then ran an event listener on the video, to check timeupdate
. For every time update, we update the width of the inner progress bar to the percent current time of the total duration of the video using this formula:
let curr = (video.currentTime / video.duration) * 100
Then we created a function called play
that we use to toggle the playing state of the video and decide which buttons to display. For this, we wrote some logic where, if the play button is clicked when the video.paused
is true
, we hide the pause button, display the play button, and play the video, else we do the opposite for each item.
For the fullscreen function, we just trigger a requestFullscreen()
function on the video element. In the download function, we created a new a
tag and assign the video URL as the href
attribute.
Next, we set the target
as _blank
to open the downloadable video in a new tab. Then we programmatically clicked the new link we created using the click()
function.
We also need to create functions to rewind or forward the video. We can do this by using the following logic:
For rewind:
video.currentTime = video.currentTime - ((video.duration/100) * 5)
For forward:
video.currentTime = video.currentTime + ((video.duration/100) * 5)
If we did everything right, we should have the following result:
Conclusion
In this article, we have learned what it means to customize an HTML5 video player and how to do it ourselves using CSS. However, you can always challenge yourself to add more features to make your video blend in even better with your own UI.
If you have any questions, feel free to drop them in the comment section below.
Is your frontend hogging your users’ CPU?
As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/
LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.
Modernize how you debug web and mobile apps — Start monitoring for free.
Basically, HTML5 audio player can’t be styled if we used the “controls” attribute inside the audio tag. But, we can easily customize the player interface if we have a custom controls function. If you have tried to style the HTML5 audio player, you may have not got the result. It is because the “controls” attribute replaces the default browser’s audio player. So, this tutorial explains how you can customize an HTML5 audio player with CSS.
Before starting the customization process, I’d suggest you browse the demo page to test the audio player. There, I have placed two audio players, one of them is the default browser player and the other one is the CSS customized audio player with custom controls.
We need to create the custom HTML tags for the audio player interface in order to style these elements with CSS. After that, we’ll get all these elements in JavaScript and attach the function. Basically, you don’t need to deal with JavaScript code as we are going to share the JavaScript file for the custom audio player. Anyhow, you can define the additional CSS styles to customize the audio player according to your needs. So, let’s create the HTML structure for a custom audio player.
In HTML, create a div tag with "audio-player"
class that will be used as a player’s container. Similarly, create elements for timeline, progress, controls, etc as described below:
<div class="audio-player"> <div class="timeline"> <div class="progress"></div> </div> <div class="controls"> <div class="play-container"> <div class="toggle-play play"> </div> </div> <div class="time"> <div class="current">0:00</div> <div class="divider">/</div> <div class="length"></div> </div> <div class="name">Music Song</div> <!-- credit for icon to https://saeedalipoor.github.io/icono/ --> <div class="volume-container"> <div class="volume-button"> <div class="volume icono-volumeMedium"></div> </div> <div class="volume-slider"> <div class="volume-percentage"></div> </div> </div> </div> </div>
In the <div class="name">
tag you can add the custom text (music name etc). Similarly, you can also add some extra elements (audio thumbnails, etc) to the above HTML.
The CSS Styles
After creating the HTML elements, now we’ll use the CSS to customize the audio player. The "audio-player "
class is the player’s container, define its width, height, background color, and font-size, etc. Similarly, define the box-shadow and keep the overflow hidden. Use the CSS display grid property in which we’ll place the player’s controls.
.audio-player { height: 50px; width: 350px; background: #444; box-shadow: 0 0 20px 0 #000a; font-family: arial; color: white; font-size: 0.75em; overflow: hidden; display: grid; grid-template-rows: 6px auto; }
Likewise, define the styles for the timeline. Set background color and keep its relative position with 100% width.
.audio-player .timeline { background: white; width: 100%; position: relative; cursor: pointer; box-shadow: 0 2px 10px 0 #0008; }
Keep the 0% width for the progress bar, set the background color, and define the 100% height.
.audio-player .timeline .progress { background: coral; width: 0%; height: 100%; transition: 0.25s; }
The "controls"
class is the container for the audio player control buttons. Define CSS styles for this container as described below:
.audio-player .controls { display: flex; justify-content: space-between; align-items: stretch; padding: 0 20px; } .audio-player .controls > * { display: flex; justify-content: center; align-items: center; }
Similarly, create the CSS styles for the toggle play/pause button. You can also set the custom icon for these buttons according to your needs.
.audio-player .controls .toggle-play.play { cursor: pointer; position: relative; left: 0; height: 0; width: 0; border: 7px solid #0000; border-left: 13px solid white; } .audio-player .controls .toggle-play.play:hover { transform: scale(1.1); } .audio-player .controls .toggle-play.pause { height: 15px; width: 20px; cursor: pointer; position: relative; } .audio-player .controls .toggle-play.pause:before { position: absolute; top: 0; left: 0px; background: white; content: ""; height: 15px; width: 3px; } .audio-player .controls .toggle-play.pause:after { position: absolute; top: 0; right: 8px; background: white; content: ""; height: 15px; width: 3px; } .audio-player .controls .toggle-play.pause:hover { transform: scale(1.1); }
Now, target the "time"
class that displays the audio duration. Display this element as CSS flex and define some padding value.
.audio-player .controls .time { display: flex; } .audio-player .controls .time > * { padding: 2px; }
The "volume-container"
contains the volume button and slider. Keep its relative position and pointer cursor property. Likewise, set the height for the volume button and display it as flex.
.audio-player .controls .volume-container { cursor: pointer; position: relative; z-index: 2; } .audio-player .controls .volume-container .volume-button { height: 26px; display: flex; align-items: center; } .audio-player .controls .volume-container .volume-button .volume { transform: scale(0.7); }
Keep the absolute position for the volume slider, set the top left value as 15px and -3px respectively. Also, define the background color, height, and z-index as mentioned beow:
.audio-player .controls .volume-container .volume-slider { position: absolute; top: 15px; left: -3px; z-index: -1; width: 0; height: 15px; background: white; box-shadow: 0 0 20px #000a; transition: 0.25s; } .audio-player .controls .volume-container .volume-slider .volume-percentage { background: coral; height: 100%; width: 75%; } .audio-player .controls .volume-container:hover .volume-slider { left: -123px; width: 120px; }
Finally, add the JavaScript file (before closing the body tag) for the custom controls to make them functional and done.
<!-- Audio Player JS --> <script src="js/player.js"></script>
That’s all! I hope this tutorial helped you to customize the HTML5 audio player with CSS. If you have any questions or need further help, let me know by comment below.
In the previous Cross browser video player article we described how to build a cross-browser HTML video player using the Media and Fullscreen APIs. This follow-up article looks at how to style this custom player, including making it responsive.
The example in action
You can find the code for the updated, styled example on GitHub, and view it live.
Preliminary modifications from the original example
This section summarizes the modifications that were made to the original video player example to make the styling task easier, before the bulk of the work was started.
HTML Markup
There are a few changes that were made to the HTML markup shown in the previous article. The custom video controls and <progress>
element are now contained within <div>
elements, rather than residing inside unordered list items.
The markup for the custom controls now looks as follows:
<div id="video-controls" class="controls" data-state="hidden">
<button id="playpause" type="button" data-state="play">Play/Pause</button>
<button id="stop" type="button" data-state="stop">Stop</button>
<div class="progress">
<progress id="progress" value="0" min="0">
<span id="progress-bar"></span>
</progress>
</div>
<button id="mute" type="button" data-state="mute">Mute/Unmute</button>
<button id="volinc" type="button" data-state="volup">Vol+</button>
<button id="voldec" type="button" data-state="voldown">Vol-</button>
<button id="fs" type="button" data-state="go-fullscreen">Fullscreen</button>
</div>
The previous article set the display
property of the video controls to block
in order to display them. This has now been changed to use a data-state
attribute, which this code already uses to handle its fullscreen implementation.
This «data-state» idea is also used for setting the current state of buttons within the video control set, which allows specific state styling.
JavaScript
As mentioned above, a data-state
attribute is used in various places for styling purposes and these are set using JavaScript. Specific implementations will be mentioned at appropriate places below.
Styling
The resultant video player style used here is rather basic — this is intentional, as the purpose is to show how such a video player could be styled and be made responsive.
Note: in some cases some basic CSS is omitted from the code examples here as its use is either obvious or not specifically relevant to styling the video player.
Basic styling
The HTML video and its controls are all contained within a <figure>
element, which is given a maximum width and height (based on the dimensions of the video used) and centered within the page:
figure {
max-width: 64rem;
width: 100%;
max-height: 30.875rem;
height: 100%;
margin: 1.25rem auto;
padding: 1.051%;
background-color: #666;
}
The video controls container itself also needs some styling so that it is set up the correct way:
.controls {
width: 100%;
height: 8.0971659919028340080971659919028%; /* of figure's height */
position: relative;
}
The height of the .controls
class is set to be (a very precise!) percentage of the enclosing <figure>
element (this was worked out with experimentation based on the required button height). Its position is also specifically set to relative
, which is required for its responsiveness (more on that later).
As mentioned earlier, a data-state
attribute is now used to indicate whether the video controls are visible or not and these also need to be styled:
.controls[data-state="hidden"] {
display: none;
}
.controls[data-state="visible"] {
display: block;
}
There are a number of properties that also need to be set for all elements within the video controls:
.controls > * {
float: left;
width: 3.90625%;
height: 100%;
margin-left: 0.1953125%;
display: block;
}
.controls > *:first-child {
margin-left: 0;
}
All elements are floated left, as they are to be aligned next to one another, and each element is set to have a width
of nearly 4% (again the actual value was calculated based on the required dimensions of the buttons), and a height
of 100%. A value for margin-left
is also set, but the first element (in this case the play/pause button) has this property overridden by the value 0.
The <div>
container for the <progress>
element also requires some specific settings; it is set to be much wider than the other child elements and its cursor value is set to be pointer:
.controls .progress {
cursor: pointer;
width: 75.390625%;
}
Buttons
The first major styling task to tackle is to make the video control’s buttons actually look like and act like real buttons.
Each button has some basic styling:
.controls button {
border: none;
cursor: pointer;
background: transparent;
background-size: contain;
background-repeat: no-repeat;
}
By default, all <button>
elements have a border, so this is removed. Since background images will be used to display appropriate icons, the background color of the button is set to be transparent, non-repeated, and the element should fully contain the image.
Simple :hover
and :focus
states are then set for each button that alters the opacity of the button:
.controls button:hover,
.controls button:focus {
opacity: 0.5;
}
To obtain appropriate button images, a set of free common control set icons was downloaded from the web. Each image was then converted to a base64 encoded string (using an online base64 image encoder), since the images are quite small, the resultant encoded strings are quite short.
Since some buttons have dual functionality, e.g. play/pause, and mute/unmute, these buttons have different states that need to be styled. As mentioned earlier, a data-state
variable is used to indicate which state such buttons are currently in.
For example, the play/pause button has the following background image definitions (the full base64 strings have been omitted for brevity):
.controls button[data-state="play"] {
background-image: url("data:image/png;base64,iVBORw0KGgoAAA…");
}
.controls button[data-state="pause"] {
background-image: url("data:image/png;base64,iVBORw0KGgoAAA…");
}
When the data-state
of the button is changed, the appropriate image will also be changed. All the other buttons are treated in a similar way.
Progress bar
The <progress>
element has the following basic style set up:
.controls progress {
display: block;
width: 100%;
height: 81%;
margin-top: 0.125rem;
border: none;
color: #0095dd;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border-radius: 2px;
}
Like the <button>
elements, <progress>
also has a default border, which is removed here. It is also given a slight rounded corner for aesthetic reasons. The color
property is also defined here as Internet Explorer uses this defined color for styling the progress bar’s background color as it increases.
As mentioned in the previous article, there is a fallback provided for browsers that do not support the <progress>
element; this also needs to be styled appropriately:
.controls progress[data-state="fake"] {
background: #e6e6e6;
height: 65%;
}
.controls progress span {
width: 0%;
height: 100%;
display: inline-block;
background-color: #2a84cd;
}
A .data-state
class is also used here when a <progress>
element is being «faked»; when it’s in this state the background color needs to be set. The internal <span>
element used as the actual progressing part of the faked progress bar has its width initially set to 0% (it is updated via JavaScript) and it also has its background color set.
There are some browser-specific properties that need to be set to ensure that Firefox and Chrome use the required color for the progress bar:
.controls progress::-moz-progress-bar {
background-color: #0095dd;
}
.controls progress::-webkit-progress-value {
background-color: #0095dd;
}
Although the same properties are set to the same value, these rules need to be defined separately, otherwise Chrome ignores it.
JavaScript
That’s really it for the immediate styling; the next task is making a number of JavaScript changes to ensure that everything works as expected.
Control visibility
The first change is simple: the data-state
for showing the video controls when JavaScript is available to the browser now needs to be set:
// Display the user defined video controls
videoControls.setAttribute("data-state", "visible");
Progress bar support
A check also needs to be made to set up the «fake» progress bar if the browser doesn’t support the <progress>
element:
const supportsProgress = document.createElement("progress").max !== undefined;
if (!supportsProgress) progress.setAttribute("data-state", "fake");
Button functionality
This section looks at the JavaScript required for implementing the button functionality.
Play/Pause and Mute
Now that the buttons actually look like buttons and have images that indicate what they do, some changes need to be made so that the «dual functionality» buttons (such as the play/pause button) are in the correct «state» and display the correct image. In order to facilitate this, a new function is defined called changeButtonState()
, which accepts a type variable indicating the button’s functionality:
function changeButtonState(type) {
if (type === "playpause") {
// Play/Pause button
if (video.paused || video.ended) {
playpause.setAttribute("data-state", "play");
} else {
playpause.setAttribute("data-state", "pause");
}
} else if (type === "mute") {
// Mute button
mute.setAttribute("data-state", video.muted ? "unmute" : "mute");
}
}
This function is then called by the relevant event handlers:
video.addEventListener(
"play",
() => {
changeButtonState("playpause");
},
false
);
video.addEventListener(
"pause",
() => {
changeButtonState("playpause");
},
false
);
stop.addEventListener("click", (e) => {
video.pause();
video.currentTime = 0;
progress.value = 0;
// Update the play/pause button's 'data-state' which allows the correct button image to be set via CSS
changeButtonState("playpause");
});
mute.addEventListener("click", (e) => {
video.muted = !video.muted;
changeButtonState("mute");
});
You might have noticed that there are new handlers where the play
and pause
events are reacted to on the video. There is a reason for this! Even though the browser’s default video control set has been turned off, many browsers make them accessible by right-clicking on the HTML video. This means that a user could play/pause the video from these controls, which would then leave the custom control set’s buttons out of sync. If a user uses the default controls, the defined Media API events — such as play
and pause
— are raised so this can be taken advantage of to ensure that the custom control buttons are kept in sync. To ensure this, a new click handler needs to be defined for the play/pause button so that it too raises the play
and pause
events:
playpause.addEventListener("click", (e) => {
if (video.paused || video.ended) {
video.play();
} else {
video.pause();
}
});
Volume
The alterVolume()
function, called when the player’s volume buttons are clicked, also changes — it now calls a new function called checkVolume()
:
function checkVolume(dir) {
if (dir) {
const currentVolume = Math.floor(video.volume * 10) / 10;
if (dir === "+" && currentVolume < 1) {
video.volume += 0.1;
} else if (dir === "-" && currentVolume > 0) {
video.volume -= 0.1;
}
// If the volume has been turned off, also set it as muted
// Note: can only do this with the custom control set as when the 'volumechange' event is raised,
// there is no way to know if it was via a volume or a mute change
video.muted = currentVolume <= 0;
}
changeButtonState("mute");
}
const alterVolume = (dir) => {
checkVolume(dir);
};
This new checkVolume()
function does the same thing as the alterVolume()
but it also sets the state of the mute button depending on the video’s current volume setting. checkVolume()
is also called when the volumechange
event is raised:
video.addEventListener(
"volumechange",
() => {
checkVolume();
},
false
);
Progress bar
A small change also needs to be made to the click handler for the <progress>
element. Since the enclosing <figure>
element now has position:relative
set on it, the calculations made by this click handler are incorrect. It now also needs to take into account the offset position of the parent element:
progress.addEventListener("click", (e) => {
const pos =
(e.pageX - progress.offsetLeft - progress.offsetParent.offsetLeft) /
progress.offsetWidth;
video.currentTime = pos * video.duration;
});
Fullscreen
The FullScreen implementation hasn’t changed.
Responsive styling
Now that the player has its basic look and feel taken care of, some other styling changes — involving media queries — need to be made in order to make it responsive.
The player currently works fairly well until displayed on a «medium» screen (e.g. 1024px/64em) or smaller. In this case, the margins and padding on the <figure>
element need to be removed so that all the available space is taken advantage of, and the buttons are a bit too small so this needs to be altered by setting a new height on the element that has the .controls
class set on it:
@media screen and (max-width: 64em) {
figure {
padding-left: 0;
padding-right: 0;
height: auto;
}
.controls {
height: 1.876rem;
}
}
This works well enough until it is viewed on a smaller screen (680px/42.5em), so another breakpoint is made here. Since the height of the .controls
class element will now vary, a fixed height is no longer required — it is therefore set to auto
. The definitions for the elements within the .controls
element now also need to be changed:
@media screen and (max-width: 42.5em) {
.controls {
height: auto;
}
.controls > * {
display: block;
width: 16.6667%;
margin-left: 0;
height: 2.5rem;
margin-top: 2.5rem;
}
.controls .progress {
position: absolute;
top: 0;
width: 100%;
float: none;
margin-top: 0;
}
.controls .progress progress {
width: 98%;
margin: 0 auto;
}
.controls button {
background-position: center center;
}
}
The .progress
container is now moved to the top of the control set via position:absolute
, so it and all the buttons need to be wider. In addition, the buttons need to be pushed below the progress container so that they are visible.
Перевод статьи Making An Audio Player With HTML5, Part 3: Microdata and Skinning с сайта demosthenes.info, c разрешения автора — Дадли Стори.
В первых двух статьях этого цикла я представил концепцию и код для собственного аудиоплеера. Прототип, который сконструирован к этому моменту – «сырой», без какого-либо оформления: HTML5 и JavaScript был написан на скорую руку, чтобы убедиться, что базовая концепция работает. В этой статье я сосредоточусь на улучшении внешнего вида плеера и добавлении микроданных, прежде чем вводить дополнительные функции в четвёртой статье.
Элементы аудио
Первым делом давайте взглянем на DOM, который у нас есть на данный момент. Скрипт во второй статье этого цикла добавил ползунок и другие функции, реализуя подход постепенного улучшения, и в результате получился следующий код:
<figure id="audioplayer"> <figcaption> <div>Track
<span>24 Ghosts III
</span></div> <div id="album">Album
<span>Ghosts III
</span></div> <div id="artist">Artist
<span>Nine Inch Nails
</span></div> <div id="time">Time
<span>00:00
</span></div> </figcaption> <div id="fader"> <input type="range" min="0" max="1" step="any" value="1"id="volumeSlider"> <button type="button">volumehigh
</button> </div> <div id="playback"> <button type="button">Play
</button> <progress min="0" max="100" value="0" id="playhead"> </progress> </div> <audio src="/assets/audio/24-ghosts-III.mp3"id="audiotrack" preload="auto"> </audio> </figure>
В этот код мы добавим микроданные, чтобы получить пользу от поисковых систем и подключить добавочный Javascript позже в этом цикле статей. Код стал таким в конце:
<figure id="audioplayer" itemprop="track"itemtype="http://schema.org/MusicRecording"> <figcaption> <div>Track
<span itemprop="name">24 Ghosts III
</span> </div> <div id="album">Album
<span itemprop="inAlbum">Ghosts III
</span> </div> <div id="artist">Artist
<span itemprop="byArtist">Nine Inch Nails
</span> </div> <div id="time">Time
<span>00:00
</span> </div> </figcaption> <meta itemprop="duration" content="PT2M29S"> <div id="fader"> <input type="range" min="0" max="1" step="any" value="1"orient="vertical" id="volumeSlider"> <button type="button">volumehigh
</button> </div> <div id="playback"> <button type="button">Play
</button> <progress min="0" max="100" value="0" id="playhead"> </progress> </div> <audio src="/assets/audio/24-ghosts-III.mp3"id="audiotrack" itemprop="audio" preload="auto"> </audio> </figure>
Оформление аудио
CSS, который применён к плееру, использует несколько техник от среднего до продвинутого уровня. Начальный CSS сбрасывает модель box-sizing, устанавливает общее оформление для аудиоплеера и полностью скрывает элемент <audio>:
* { box-sizing:border-box
;} figure#audioplayer { border:1px solid #000
; background: url(dark_wall.png)#333
; overflow:hidden
; width:27rem
; padding:.4rem
; margin:2rem auto
; } figure#audioplayer audio { width:0
; height:0
; }
Далее оформим элементы с различной информацией внутри плеера, установив им границы со всех сторон, чтобы между ними был разделитель. При помощи CSS (к сожалению, нестандартного — прим. перев.) элемент input
с типом range
сделан вертикальным для Webkit и Chrome:
figure#audioplayer figcaption { width:21.5rem
; font-size:0
; margin:.45rem
; background:#000
; float:left
; border:1px solid #555
; text-align:left
;} figure#audioplayer figcaption div { background:#000
; color:#fff
; padding:.8rem
; font-family:Avenir, Helvetica, sans-serif
; text-transform:uppercase
; font-size:.8rem
; display:inline-block
;} figure#audioplayer figcaption div span { display:block
; font-size:1.3rem
; text-indent:1rem
;} div#album { border-top:1px solid #555
; border-bottom:1px solid #555
; width:100%
;} div#time { width:7.55rem
; border-left:1px solid #555
;} input#volumeSlider{ -webkit-appearance:slider-vertical
; width:35px
; }
Для кнопок используется иконочный шрифт с семантическими лигатурами, чтобы превратить их текст в изображение.
figure#audioplayer button { width:3rem
; height:3rem
; background:#000
; color:#fff
; border:none
; -webkit-font-feature-settings: "liga",
"dlig"; font-feature-settings: "liga",
"dlig";} #playback { clear:both
;} div#fader { display:inline-block
;}
Также я сделал оформление для элемента <progress>. Здесь используется HSL, чтобы в будущем (если потребуется) нам было легче менять цвет.
#playback progress { margin-left:1rem
; width:20rem
; height:12px
; -webkit-appearance:none
; -moz-appearance:none
; appearance:none
; background-color:#888
; border:none
; color:hsl(44,100%,44%)
; } progress::-webkit-progress-bar,
progress::-moz-progress-bar,
progress::progress-bar { background:hsl(44,100%,44%)
; } progress::-webkit-progress-value { background:hsl(44,100%,44%)
; } progress::-moz-progress-bar { background-color:hsl(44,100%,44%)
; }
Наконец, плеер поддерживает адаптивность, перемещая элементы в нужное место и уменьшая отступы при сужении области просмотра:
@media screen and (max-width:500px){ div#time { display:block
!important; border-top:1px solid #555
; width:100%
;} figure#audioplayer { width:100%
; padding:.2rem
;} figure#audioplayer figcaption div { padding:.4rem
;} } @media screen and (max-width:450px){ figure#audioplayer figcaption { width:16rem
; } #playback progress { width:220px
; } } @media screen and (max-width:400px) { figure#audioplayer figcaption { width:14rem
; } }
See the Pen Simple HTML5 Audio Player In Pure JS & CSS by Dudley Storey (@dudleystorey) on CodePen.
В следующей статье я буду использовать Web Audio API, чтобы добавить и анимировать отображение шкалы для правого и левого каналов плеера.
P.S. Это тоже может быть интересно: