・JavaScript コード
class HLSVideoHandler {
constructor(options = {}) {
this.debug = options.debug || false;
this.enableWorker = options.enableWorker || true;
this.maxRetries = options.maxRetries || 3;
this.retryDelay = options.retryDelay || 1000;
this.initialized = false;
}
async initialize() {
if (typeof Hls === 'undefined') {
try {
await this.loadHLSScript();
this.initialized = true;
} catch (error) {
console.error('Failed to load HLS.js:', error);
throw error;
}
} else {
this.initialized = true;
}
}
loadHLSScript() {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/hls.js/1.4.10/hls.min.js';
script.async = true;
script.onload = () => resolve();
script.onerror = () => reject(new Error('Failed to load HLS.js script'));
document.head.appendChild(script);
});
}
async setupPlayer(videoElement, playlistUrl) {
if (!this.initialized) {
await this.initialize();
}
if (!videoElement) {
throw new Error('No video element provided');
}
if (!Hls.isSupported()) {
return this.setupNativePlayer(videoElement, playlistUrl);
}
try {
const hls = new Hls({
debug: this.debug,
enableWorker: this.enableWorker
});
hls.loadSource(playlistUrl);
hls.attachMedia(videoElement);
return hls;
} catch (error) {
console.error('Error setting up HLS:', error);
return this.setupNativePlayer(videoElement, playlistUrl);
}
}
setupNativePlayer(videoElement, playlistUrl) {
if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
videoElement.src = playlistUrl;
return true;
}
return false;
}
}
window.HLSVideoHandler = HLSVideoHandler;
・HTML コード
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HLS Video Player Demo</title>
<style>
.video-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
video {
width: 100%;
}
</style>
</head>
<body>
<div class="video-container">
<h1>HLS Video Player デモ</h1>
<video id="video" controls playsinline></video>
</div>
<script src="hls-video-handler.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const videoElement = document.getElementById('video');
const hlsHandler = new HLSVideoHandler({ debug: true });
try {
await hlsHandler.setupPlayer(videoElement, 'https://video.bsky.app/watch/did%3Aplc%3A47ssgpmbvhxr2ia2hy4rsan3/bafkreiepps3hzer26qun2ywbnepacftgy4vf32extbnaqzufgfrukllata/playlist.m3u8');
} catch (error) {
console.error('Failed to initialize video player:', error);
}
});
</script>
</body>
</html>