JavaScript Library for Playing HLS | Generated by AI

Home PDF

It seems like you’re asking about how to use the hls.js library, specifically version ^0.7.6, which is a JavaScript library for playing HLS (HTTP Live Streaming) video streams in browsers. I’ll provide a concise guide on how to set it up and use it based on general knowledge of the library. Note that version 0.7.6 is quite old (released around 2017), so some features or APIs might differ from the latest versions. If you need specifics tied to that exact version, let me know, and I can refine the answer further!

Steps to Use hls.js (v0.7.6)

1. Install or Include the Library

You can include hls.js in your project in one of these ways:

2. Set Up Your HTML

You need a <video> element in your HTML to attach the HLS stream to:

<video id="video" controls></video>

3. Initialize hls.js

Here’s a basic example of how to use hls.js to load and play an HLS stream (e.g., an .m3u8 file):

// Check if the browser supports HLS natively (e.g., Safari)
// If not, use hls.js
var video = document.getElementById('video');
var videoSrc = 'https://example.com/playlist.m3u8'; // Replace with your HLS URL

if (Hls.isSupported()) {
    var hls = new Hls();
    hls.loadSource(videoSrc);
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function () {
        video.play();
    });
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    // For browsers with native HLS support (e.g., Safari)
    video.src = videoSrc;
    video.addEventListener('loadedmetadata', function () {
        video.play();
    });
}

4. Key Concepts

5. Example with Error Handling

To make it more robust:

var video = document.getElementById('video');
var videoSrc = 'https://example.com/playlist.m3u8';

if (Hls.isSupported()) {
    var hls = new Hls();
    hls.loadSource(videoSrc);
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function () {
        video.play();
    });
    hls.on(Hls.Events.ERROR, function (event, data) {
        console.error('HLS Error:', data);
        if (data.fatal) {
            switch (data.type) {
                case Hls.ErrorTypes.NETWORK_ERROR:
                    console.log('Network error, retrying...');
                    hls.startLoad();
                    break;
                case Hls.ErrorTypes.MEDIA_ERROR:
                    console.log('Media error, recovering...');
                    hls.recoverMediaError();
                    break;
                default:
                    hls.destroy();
                    break;
            }
        }
    });
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    video.src = videoSrc;
}

Notes for Version ^0.7.6

6. Testing

If you have a specific use case or issue (e.g., integrating with a framework, handling subtitles, etc.), let me know, and I’ll tailor the response further!


Back 2025.03.04 Donate