92 lines
3.0 KiB
JavaScript
92 lines
3.0 KiB
JavaScript
/**
|
|
* HLS Player Utility
|
|
* This script adds HLS playback capability to browsers using the native
|
|
* HLS support in Safari/iOS or hls.js library in other browsers.
|
|
*/
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
// Find all video elements on the page
|
|
const videos = document.querySelectorAll('video');
|
|
|
|
// Skip processing if no videos are found
|
|
if (videos.length === 0) return;
|
|
|
|
// Function to check for native HLS support
|
|
function isHlsSupported() {
|
|
const video = document.createElement('video');
|
|
return video.canPlayType('application/vnd.apple.mpegURL') ||
|
|
video.canPlayType('application/x-mpegURL');
|
|
}
|
|
|
|
// Function to initialize HLS.js for a video element
|
|
function setupHlsJs(video) {
|
|
// Only process videos with HLS sources
|
|
const hlsSource = Array.from(video.querySelectorAll('source'))
|
|
.find(source => source.src.includes('.m3u8'));
|
|
|
|
if (!hlsSource) return;
|
|
|
|
// Don't setup HLS.js if browser has native support
|
|
if (isHlsSupported()) return;
|
|
|
|
// Check if HLS.js is loaded
|
|
if (typeof Hls !== 'undefined') {
|
|
// Check if HLS.js is supported in this browser
|
|
if (Hls.isSupported()) {
|
|
const hls = new Hls({
|
|
maxBufferLength: 30,
|
|
maxMaxBufferLength: 60
|
|
});
|
|
|
|
hls.loadSource(hlsSource.src);
|
|
hls.attachMedia(video);
|
|
|
|
hls.on(Hls.Events.MANIFEST_PARSED, function() {
|
|
if (video.autoplay) {
|
|
video.play()
|
|
.catch(error => console.warn('Auto-play failed:', error));
|
|
}
|
|
});
|
|
|
|
// Handle errors
|
|
hls.on(Hls.Events.ERROR, function(event, data) {
|
|
console.warn('HLS error:', data);
|
|
|
|
// If fatal error, try to recover
|
|
if (data.fatal) {
|
|
switch (data.type) {
|
|
case Hls.ErrorTypes.NETWORK_ERROR:
|
|
console.log('Fatal network error, trying to recover...');
|
|
hls.startLoad();
|
|
break;
|
|
case Hls.ErrorTypes.MEDIA_ERROR:
|
|
console.log('Fatal media error, trying to recover...');
|
|
hls.recoverMediaError();
|
|
break;
|
|
default:
|
|
// Cannot recover
|
|
hls.destroy();
|
|
// Fall back to MP4 if available
|
|
const mp4Source = Array.from(video.querySelectorAll('source'))
|
|
.find(source => source.type === 'video/mp4');
|
|
if (mp4Source) {
|
|
video.src = mp4Source.src;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
});
|
|
} else {
|
|
console.warn('HLS.js is not supported in this browser');
|
|
}
|
|
} else {
|
|
console.warn('HLS.js is not loaded');
|
|
// You might want to dynamically load hls.js here
|
|
// const script = document.createElement('script');
|
|
// script.src = '/static/js/vendor/hls.min.js';
|
|
// document.head.appendChild(script);
|
|
}
|
|
}
|
|
|
|
// Initialize each video
|
|
videos.forEach(setupHlsJs);
|
|
});
|