M3U8 Video Merge to MP4 Tutorial
Introduces common approaches for organizing M3U8 segmented videos into MP4 files, including online tools, player verification methods, and common developer solutions.
Read More →Master the core technology of HLS streaming media playback
HLS.js is an open-source JavaScript library that implements an HLS (HTTP Live Streaming) client, capable of playing HLS streaming media in browsers that support MSE (Media Source Extensions). Developed and maintained by Dailymotion, it is currently one of the most popular web-based HLS playback solutions.
Unlike Safari browsers that natively support HLS, browsers like Chrome, Firefox, and Edge do not natively support the HLS format and require JavaScript libraries like HLS.js to implement playback functionality.
The working principles of HLS.js can be divided into the following core steps:
HLS.js first fetches the M3U8 playlist file via HTTP request, then parses its content, including:
After parsing the playlist, HLS.js downloads TS segments sequentially according to playback order and appends the data to the SourceBuffer of MediaSource. At the same time, it maintains a buffer queue to ensure playback continuity.
HLS.js monitors network bandwidth and buffer status in real-time, automatically switching to an appropriate bitrate video stream based on a preset algorithm to ensure a balance between playback smoothness and quality.
Below is the simplest example of using HLS.js, requiring only a few lines of code to play HLS video streams in a web page.
You can import HLS.js directly via CDN, which is the simplest way:
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
Add a video element to the page:
<video id="video" controls playsinline></video>
Use the following code to initialize HLS.js and load the video:
const video = document.getElementById('video');
const videoUrl = 'https://example.com/stream.m3u8';
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(videoUrl);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function() {
video.play();
});
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoUrl;
video.addEventListener('loadedmetadata', function() {
video.play();
});
}
HLS.js provides a wealth of configuration options that can be adjusted according to actual needs:
Suitable for live streaming scenarios, can effectively reduce playback latency:
const hls = new Hls({
lowLatencyMode: true,
liveSyncDurationCount: 3
});
Specify the default quality level for playback:
const hls = new Hls({
startLevel: 2, // Start from the 3rd quality level
autoStartLoad: true
});
Adjust buffer size to balance memory usage and playback stability:
const hls = new Hls({
maxBufferLength: 30, // Maximum buffer of 30 seconds
maxMaxBufferLength: 60 // Maximum maximum buffer of 60 seconds
});
HLS.js provides a comprehensive event system that can listen to various state changes and errors:
hls.on(Hls.Events.ERROR, function(event, data) {
if (data.fatal) {
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
console.log('Network error, attempting to recover...');
hls.startLoad();
break;
case Hls.ErrorTypes.MEDIA_ERROR:
console.log('Media error, attempting to recover...');
hls.recoverMediaError();
break;
default:
console.log('Unrecoverable error');
hls.destroy();
break;
}
}
});
When the page unloads or switches videos, remember to call the destroy method to release resources:
window.addEventListener('beforeunload', function() {
if (hls) {
hls.destroy();
}
});
Ensure the M3U8 and TS file server is configured with the correct CORS headers, otherwise HLS.js cannot load resources. The following response headers need to be allowed:
Access-Control-Allow-OriginAccess-Control-Allow-CredentialsTo improve user experience, it is recommended to set a reasonable initial quality based on the user's network environment, or let users manually select.
In production environments, be sure to listen for ERROR events and perform error recovery or degradation processing when necessary, providing users with friendly prompts.
HLS.js is a powerful, actively community-supported open-source HLS playback library, and the preferred solution for implementing HLS streaming media playback in web pages. Through the introduction in this article, we believe you now have a comprehensive understanding of the basic usage of HLS.js.
If you want to quickly experience HLS playback functionality, you can directly use our M3U8 online player, which can play HLS video streams in your browser without writing any code.
More great articles and useful tools
Introduces common approaches for organizing M3U8 segmented videos into MP4 files, including online tools, player verification methods, and common developer solutions.
Read More →Comprehensive coverage of PC, mobile, and web platforms, recommending solutions like VLC, PotPlayer, and web-based online players, with common troubleshooting methods.
Read More →Beginner-friendly guide teaching you how to watch FLV and RTMP live streams through web players, including live stream principles, operation tutorials, and screenshot tips.
Read More →Use our free M3U8 online player, no coding required, play HLS video streams directly in your browser
Try It Now ➡