HLS.js options to support subtitle

CK CK 3788 
Created at  
513 0 0

To configure HLS.js to support subtitles, you need to include specific options in your HLS.js setup. Here’s how you can do it:

 

1. Include HLS.js in Your Project

Ensure you have HLS.js included in your project, either via a CDN or by installing it using npm/yarn.

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

Or if using npm/yarn:

npm install hls.js

 

2. Basic HLS.js Setup with Subtitle Support

<video id="video1" controls preload="auto" width="720" height="420"></video><br>
<style>
video::cue {
	font-size: var(--cue-font-size, 16px); /* Default to 16px */
	font-family: Arial, sans-serif;
}
</style>
<script type="text/javascript">
function adjustCueFontSize() {
	const video = document.getElementById('video1');
	const videoWidth = video.clientWidth;
	const fontSize = videoWidth * 0.03; // Adjust this multiplier as needed
	video.style.setProperty('--cue-font-size', fontSize + 'px');
	console.log( "adjustCueFontSize", fontSize);
}

// Adjust font size when the video size changes
document.getElementById('video1').addEventListener('loadedmetadata', adjustCueFontSize);
document.getElementById('video1').addEventListener('resize', adjustCueFontSize);

// Monitor resizing using ResizeObserver for dynamic content
const resizeObserver = new ResizeObserver(() => adjustCueFontSize());
resizeObserver.observe(document.getElementById('video1'));

adjustCueFontSize(); // Initial adjustment


function load_video( streaming_url )
{
	var video1 = document.getElementById("video1");
	if (Hls.isSupported())
	{
		var _hlsOptions =
		{
			"debug": false,
			xhrSetup: function(xhr, url)
			{
			},
			fetchSetup: (url, headers) => {
				return fetch(url, { headers }).then(response => {
					return response;
				});
			}
		};
		
		var hlsvideo1 = new Hls(_hlsOptions);
		hlsvideo1.loadSource( streaming_url );
		hlsvideo1.attachMedia(video1);

		// Enable subtitle support
		hlsvideo1.subtitleDisplay = true;

		// Set up event listeners for subtitle tracks
		hlsvideo1.on(
			Hls.Events.SUBTITLE_TRACKS_UPDATED,
			function (event, data) {
				const subtitleTracks = data.subtitleTracks;
				console.log('Available subtitle tracks:', subtitleTracks);

				// Set the default subtitle track, if desired
				if (subtitleTracks.length > 0) {
					hlsvideo1.subtitleTrack = 0; // Select the first subtitle track by default
				}
			}
		);

		// Listen for subtitle track changes
		hlsvideo1.on(
			Hls.Events.SUBTITLE_TRACK_SWITCH,
			function (event, data)
			{
				console.log('Subtitle track switched to:', data.id);
			}
		);

		hlsvideo1.on(Hls.Events.SUBTITLE_TRACK_LOADED, function () {
			console.log('Subtitle track loaded');
		});
	}
}
load_video( "{$url}" );

</script>

 

This HTML and JavaScript code is designed to load and play a video with dynamically adjustable subtitle (cue) font size based on the video's width. Here's a summary of the key functionalities:

  1. Video Setup:
    • A <video> element is defined with controls and a specified width and height.
    • The video's subtitle (cue) font size is set via CSS and dynamically adjusted using a CSS variable (--cue-font-size).
  2. Dynamic Subtitle Font Size:
    • The adjustCueFontSize function calculates the font size based on the video's width (3% of the width by default) and applies this size to the subtitles.
    • This function is triggered when the video's metadata is loaded, or the video is resized.
    • A ResizeObserver is used to monitor the video element for any resizing and to adjust the font size dynamically.
  3. HLS Video Streaming:
    • The load_video function initializes the video player with support for HLS (HTTP Live Streaming).
    • If HLS is supported, the video stream is loaded from a given URL, and the video is attached to the video element.
    • Subtitle support is enabled, with event listeners to handle and log subtitle tracks and changes, such as when tracks are updated or switched.
  4. Subtitle Management:
    • The script manages subtitle tracks, setting the first track as the default and handling events when subtitle tracks are loaded or switched.

 

3. Switching Subtitle Tracks

If you want to switch between subtitle tracks programmatically, you can do so by setting the hls.subtitleTrack property:

// Switch to the second subtitle track (index starts from 0)
hls.subtitleTrack = 1;

 

Tags HLS.js Subtitle Subtitle Font subtitleTrack Facebook X
Comments 0
Similar posts
  1. When HLS.js need to load m3u8 URL redirecting to the different URL (302 Redirection)
    659
  2. HLS.js code to reload when user face bufferfull error
    702
  3. HLS.js code to reload video when levelLoadTimeOut occurs
    703
  4. Change the manifest loading timeout in HLS.js
    1,028
  5. How do I display trickplay images with hls.js that elaborated at EXT-X-IMAGE-STREAM-INF in m3u8
    800
  6. Limit Maximum Resolution in HLS.js
    663
  7. Disabling Audio Tracks in HLS.js
    371
  1. How do I create animated background for Google Meet?
    19,707
  2. Secure HLS encoding using AES-128 encryption with FFmpeg
    1,130
  3. Machine Learning Models for Ad Detection from a Video Stream
    185
  4. Unlock Flawless HLS Audio Sync: The Power of #EXT-X-INDEPENDENT-SEGMENTS
    372
  5. NVIDIA CUDA library which can be integrated with C/C++
    375
  6. Approaches to Scene Detection in Video Processing
    643
  7. FFmpeg CLI to remove audio track from MP4
    540
  8. Building GPU as a Service aka Dockerized GPU
    1,566
  9. IAB Categories (a.k.a. OpenRTB Code)
    1,012
  10. FFmpeg library that can be directly integrated into C/C++/Rust/Python without CLI
    2,056
  11. HTTP Live Streaming (HLS) was developed by Apple as part of QuickTime X in iOS3.0, and became an official standard (RFC 8126) in 2017
    593
  12. Progressive MP4 is an application of streaming techniques using the standardized MP4 container invented by MPEG LA consortium
    1,071
  13. FFmpeg CLI to mix two different audios in a single audio file such as mp3
    599
  14. FFmpeg CLI to merge a video only mp4 and mp3 audio file
    332
  15. FFmpeg CLI to convert a video file to an MP3 audio file
    345
  16. When HLS.js need to load m3u8 URL redirecting to the different URL (302 Redirection)
    659
  17. HLS.js code to reload when user face bufferfull error
    702
  18. HLS.js code to reload video when levelLoadTimeOut occurs
    703
  19. Change the manifest loading timeout in HLS.js
    1,028
  20. HLS.js Custom Error Handler to load Main Manifest from unstable HLS Live Stream
    1,427
  21. Mastering Audio Sync: Keyframes, GOP, FFmpeg, and HLS Explained
    535
  22. How do I display trickplay images with hls.js that elaborated at EXT-X-IMAGE-STREAM-INF in m3u8
    800
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,707
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    197
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    221
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    575
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    326
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252