Html5 audio player
Перейти к навигации
Перейти к поиску
Для потокового вещания на Icecast не нашел нормальных плееров, написал свои. Они поддерживают полноценный стоп, при котором прекращается кэширование.
Минимальный скрипт плеера на голом js с поддержкой stop
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="player-via">
<audio id="player">
<source id="s1" src="">
<source id="s2" src="" type="audio/mpeg">
</audio>
</div>
<div>
<button onclick="play()">Воспроизведение</button>
<button onclick="pause()">Пауза</button>
</div>
</body>
<script type="text/javascript">
var sourceElement1 = document.getElementById("s1");
var sourceElement2 = document.getElementById("s2");
var originalSourceUrl1 = "http://online.uniton.ru:8300/RadioUniton32.pls";
var originalSourceUrl2 = "http://online.uniton.ru:8300/RadioUniton32";
var audioElement = document.querySelector("audio");
function pause() {
sourceElement1.setAttribute("src", "");
sourceElement2.setAttribute("src", "");
audioElement.pause();
// settimeout, otherwise pause event is not raised normally
setTimeout(function () {
audioElement.load(); // This stops the stream from downloading
});
}
function play() {
if (!sourceElement1.getAttribute("src") && !sourceElement2.getAttribute("src")) {
var date = new Date();
sourceElement1.setAttribute("src", originalSourceUrl1+"?"+date.getTime());
sourceElement2.setAttribute("src", originalSourceUrl2+"?"+date.getTime());
audioElement.load(); // This restarts the stream download
}
audioElement.play();
}
</script>
</html>
Файл RadioUniton32.pls:
[playlist] numberofentries=1 File1=http://online.uniton.ru:8300/RadioUniton32 Title1=Radio Uniton Length1=-1 version=2
Полнофункциональный плеер на jQuery с поддержкой stop
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="player-rrv">
<audio class="player" preload="none">
<!--Для того что бы при перезагрузке страницы не играли артефакты, при загрузке src должен быть пустым-->
<!--По этому помещаем url потока в data-src -->
<source class="src-stream" src="" data-src="http://online.uniton.ru:8300/RadioUniton32.pls"> <!--Для телефонов, по сути ссылка на файл плей листа потока ниже-->
<source class="src-stream" src="" data-src="http://online.uniton.ru:8300/RadioUniton32" type="audio/mpeg"> <!--Для компьютеров-->
</audio>
<button class="play">Play</button>
<button class="quieter">Vol-</button>
<button class="louder">Vol+</button>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('.player-rrv').each(function(){
var audioElement = jQuery(this).find('.player').first();
// Play - Stop
jQuery(this).find('.play').on('click', function() {
// если src не задан, значит можно включить player
if (!jQuery(this).siblings('.player').find('.src-stream').first().attr('src')) {
var date = new Date();
// Для того что бы браузер корректно отрабатывал, добавляем к потоку соль в виде кол-ва секунд с начала эпохи
jQuery(this).siblings('.player').find('.src-stream').each(function(){
jQuery(this).attr('src', jQuery(this).data('src')+'?'+date.getTime());
});
jQuery(this).siblings('.player').trigger('load'); // Загрузим поток
jQuery(this).text('stop'); // Сменим надпись кнопки
jQuery(this).attr('class',"stop"); // Сменим стиль кнопки
jQuery(this).siblings('.player').trigger('play'); // Запустим плеер
} else {
jQuery(this).siblings('.player').trigger('pause'); // Включим паузу
// Отчистим src потоков
jQuery(this).siblings('.player').find('.src-stream').each(function(){
jQuery(this).attr('src', '');
});
jQuery(this).siblings('.player').trigger('load'); // Рестартанем загрузку (уже с пустыми src)
jQuery(this).text('start'); // Сменим надпись кнопки
jQuery(this).attr('class',"play"); // Сменим стиль кнопки
}
});
// Уменьшить громкость
jQuery(this).find('.quieter').on('click', function() {
var vol = jQuery(this).siblings('.player').prop('volume');
vol = (vol-0.1 > 0) ? vol-0.1 : 0;
jQuery(this).siblings('.player').prop('volume', vol);
});
// Увеличить громкость
jQuery(this).find('.louder').on('click', function() {
var vol = jQuery(this).siblings('.player').prop('volume');
vol = (vol+0.1 < 1) ? vol+0.1 : 1;
jQuery(this).siblings('.player').prop('volume', vol);
});
});
// Если нужен автозапуск первого плеера, раскомментируем следующую строчку
//jQuery('.player-rrv').find('.play').first().trigger( 'click' )
});
</script>
</html>