Table of Contents |
---|
...
Описание
Данный плеер пример демонстрирует возможности WCS по преобразованию опубликованного на сервере потока в HLS и воспроизведению его в браузере при помощи библиотеки HLS.js. Нарезка потока в HLS запускается автоматически, при обращении к потоку, опубликованному на сервере, по HLS URL, например, для потока на рисунке ниже http`https://localhost:8082/test/test.m3u8test1.flashphoner.com:8445/test/test.m3u8`
Начиная со сборки 2.0.244, пример поддерживает следующие параметры:
- llhls - включает поддержку Low Latency HLS:
false
илиtrue
- src - полный HLS URL потока для проигрывания, должен быть закодирован при помощи URI encode, например
https%3A%2F%2Ftest1.flashphoner.com%3A8445%2Ftest%2Ftest.m3u8
- autoplay - автоматически запустить проигрывание указанного HLS URL, при этом все поля ввода и кнопки скрываются:
false
(по умолчанию) илиtrue
Пример открытия плеера с параметрами, как на скриншоте выше (ссылка в поле Permalink
)
Code Block | ||
---|---|---|
| ||
https://test1.flashphoner.com:8444/client2/examples/demo/streaming/hls-js-player/hls-js-player.html?llhls=false&src=https%3A%2F%2Ftest1.flashphoner.com%3A8445%2Ftest%2Ftest.m3u8 |
Пример вызова плеера с автозапуском
Code Block | ||
---|---|---|
| ||
https://test1.flashphoner.com:8444/client2/examples/demo/streaming/hls-js-player/hls-js-player.html?llhls=false&src=https%3A%2F%2Ftest1.flashphoner.com%3A8445%2Ftest%2Ftest.m3u8&autoplay=true |
При этом воспроизведение потока будет запущено автоматически, с отключенным звуком. Для включения звука зритель должен использовать кнопку регулятора громкости в интерфейсе плеера.
Код примера
Код данного примера находится на сервере по следующему пути:
...
Для разбора кода возьмем версию файла hls-js-player.js с хешем ecbadc3 1703e13, которая находится здесь и доступна для скачивания в соответствующей сборке 2.0.212244.
1.
...
Загрузка страницы плеера
Code Block | ||||
---|---|---|---|---|
| ||||
function initPageconst loadPlayerPage = function() { $loadPage("#header").text("HLS.JS Player Minimal"); $("#urlServer").val(getHLSUrl()); ...../hls-player/player-page.html", "playerPage", initPage ); } |
2.
...
...
Инициализация HTML-страницы плеера
Если браузер не поддерживает технологию MSE, плеер не будет инициализирован, и будет выведено предупреждение
Code Block | ||||
---|---|---|---|---|
| ||||
const initPage = function initPage(() { if (playSrc) { setValue("fullLink", decodeURIComponent(playSrc)); } else if (autoplay) { ...console.warn("No HLS URL set, autoplay disabled"); autoplay = false; } if (llHlsEnabled) { setCheckbox("llHlsEnabled", llHlsEnabled); } remoteVideo = document.getElementById('remoteVideo'); remoteVideo.style ="background-color: lightgrey;"; } |
3. Определение имени потока (должен быть опубликован на сервере)
encodeURIComponent() code
Code Block | ||||
---|---|---|---|---|
| ||||
function playBtnClick() { if (validateForm())if (Hls.isSupported()) { console.log("Using HLS.JS " + Hls.version); if (autoplay) { // There should not be any visible item on the page unless player hideAllToAutoplay(); // The player should use all available page width setUpPlayerItem(true); // The player should be muted to automatically start playback initVideoPlayer(remoteVideo, true); playBtnClick(); } else { setText("header", "HLS.JS Player Minimal"); showItem("llHlsMode"); displayCommonItems(); setUpButtons(); enablePlaybackStats(); // The player should have a maximum fixed size setUpPlayerItem(false); // The player can be unmuted because user should click Play button initVideoPlayer(remoteVideo, false); } } else { var streamName = $('#playStream').val(setText("notifyFlash", "Your browser doesn't support MSE technology required to play video"); disableItem("applyBtn"); toggleInputs(false); streamName = encodeURIComponent(streamName);} } |
3. Инициализация видео элемента для проигрывания
Code Block | ||||
---|---|---|---|---|
| ||||
const initVideoPlayer = function(video, muted) { if (video) { video.style.backgroundColor = "black"; video.muted = muted; } } |
4. Формирование URL HLS-потока
Если указаны ключ и токен авторизации, они будут включены в URL потока
Code Block | ||||
---|---|---|---|---|
| ||||
function playBtnClick(const getVideoSrc = function(src) { let videoSrc = src; if (validateForm()) { let streamName ... = getValue('playStream'); streamName = encodeURIComponent(streamName); var videoSrc = $getValue("#urlServerurlServer").val() + '/' + streamName + '/' + streamName + '.m3u8'; varlet key = $getValue('#keykey').val(); varlet token = $getValue("#tokentoken").val(); if (key.length > 0 && token.length > 0) { videoSrc += "?" + key + "=" + token; } } ...setValue("fullLink", videoSrc); }return videoSrc; } |
5. Настройка HLS. Запуск js плеера
Если браузер не поддерживает технологию MSE, плеер не запустится, будет выведено предупреждение
Code Block | ||||
---|---|---|---|---|
| ||||
function playBtnClick(const getHlsConfig = function(llHlsEnabled) { let if (validateForm())config = { ... lowLatencyMode: false, enableWorker: true, if (Hls.isSupported()) { backBufferLength: 90, manifestLoadingTimeOut: 15000 }; console.log("Low Latency HLS: "+llHlsEnabled) hlsPlayer = new Hls(getHlsConfig(llHlsEnabled));if(llHlsEnabled) { // Here we configure hlsPlayer.loadSource(videoSrc); HLS.JS for lower latency config hlsPlayer.attachMedia(remoteVideo);= { hlsPlayer.on(Hls.Events.MANIFEST_PARSED, function() { lowLatencyMode: llHlsEnabled, enableWorker: true, console.log("Play with HLS.js"); backBufferLength: 90, remoteVideo.play();liveBackBufferLength: 0, liveSyncDuration: 0.5, onStarted(); liveMaxLatencyDuration: 5, });liveDurationInfinity: true, } else {highBufferWatchdogPeriod: 1, $("#notifyFlash").text("Your browser doesn't support MSE technology required to play video")manifestLoadingTimeOut: 15000 }; } } }return config; } |
6. Остановка воспроизведенияЗапуск плеера
Code Block | ||||
---|---|---|---|---|
| ||||
function stopBtnClickconst playBtnClick = function() { iflet (hlsPlayervideoSrc != null) {getVideoSrc(getValue("fullLink")); console.log("Stop HLS segments loading"); if (videoSrc) { llHlsEnabled = hlsPlayer.stopLoad(getCheckbox("llHlsEnabled"); hlsPlayer = null new Hls(getHlsConfig(llHlsEnabled)); } if (remoteVideo != nullhlsPlayer.on(Hls.Events.MANIFEST_PARSED, function() { console.log("StopPlay HTML5with playerHLS.js"); remoteVideo.pauseplay(); remoteVideo.currentTime = 0}); remoteVideo.removeAttribute('src'); onplaying = () => { remoteVideo.load(); } console.log("playing event onStopped(fired"); } |
7. Настройка HLS.js плеера
Code Block | ||||
---|---|---|---|---|
| ||||
function getHlsConfig(llHlsEnabled) { var config = {displayPermalink(videoSrc); lowLatencyMode: false,} enableWorker: true,hlsPlayer.loadSource(videoSrc); backBufferLength: 90hlsPlayer.attachMedia(remoteVideo); }; ifonStarted(llHlsEnabled); { // Here we configure HLS.JS for lower latency } } |
7. Остановка воспроизведения
Code Block | ||||
---|---|---|---|---|
| ||||
const stopBtnClick = function() { if config(hlsPlayer != null) { console.log("Stop HLS lowLatencyMode: llHlsEnabled,segments loading"); enableWorker: true,hlsPlayer.stopLoad(); hlsPlayer backBufferLength: 90,= null; } if (remoteVideo != liveBackBufferLength: 0,null) { console.log("Stop liveSyncDuration: 0.5,HTML5 player"); liveMaxLatencyDuration: 5,remoteVideo.pause(); remoteVideo.currentTime liveDurationInfinity: true,= 0; highBufferWatchdogPeriod: 1,remoteVideo.removeAttribute('src'); }remoteVideo.load(); } return configonStopped(); } |