68 lines
2.1 KiB
JavaScript
68 lines
2.1 KiB
JavaScript
function initializeHlsVideo(videoElementId, sourceUrl) {
|
|
if (!Hls.isSupported()) return;
|
|
|
|
const video = document.getElementById(videoElementId);
|
|
let hls = null;
|
|
let reconnectInterval = null;
|
|
|
|
const initHLS = () => {
|
|
if (hls) hls.destroy();
|
|
if (reconnectInterval) {
|
|
clearInterval(reconnectInterval);
|
|
reconnectInterval = null;
|
|
}
|
|
|
|
hls = new Hls();
|
|
hls.loadSource(sourceUrl);
|
|
hls.attachMedia(video);
|
|
|
|
hls.on(Hls.Events.MANIFEST_PARSED, () => {
|
|
video.play().catch(err => console.warn('Autoplay error:', err));
|
|
});
|
|
|
|
hls.on(Hls.Events.ERROR, (event, data) => {
|
|
console.warn("HLS error:", data);
|
|
if (data.fatal) {
|
|
switch (data.type) {
|
|
case Hls.ErrorTypes.NETWORK_ERROR:
|
|
console.warn("Network error: retrying...");
|
|
if (!reconnectInterval) {
|
|
reconnectInterval = setInterval(() => {
|
|
console.log("Reconnecting HLS...");
|
|
initHLS();
|
|
}, 1000);
|
|
}
|
|
break;
|
|
case Hls.ErrorTypes.MEDIA_ERROR:
|
|
console.warn("Media error: recovering...");
|
|
hls.recoverMediaError();
|
|
break;
|
|
default:
|
|
console.warn("Fatal error: restarting...");
|
|
initHLS();
|
|
break;
|
|
}
|
|
}
|
|
});
|
|
};
|
|
|
|
initHLS();
|
|
|
|
const syncToLive = () => {
|
|
const liveEdge = hls.liveSyncPosition;
|
|
if (liveEdge && Math.abs(video.currentTime - liveEdge) > 2) {
|
|
console.log("Resyncing to live...");
|
|
video.currentTime = liveEdge;
|
|
}
|
|
};
|
|
|
|
setInterval(syncToLive, 3000);
|
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (document.visibilityState === 'visible') {
|
|
console.log("Tab visible. Reinitializing HLS...");
|
|
initHLS();
|
|
}
|
|
});
|
|
}
|