[Go Make Things] Looping HLS video

HLS, or HTTP Live Streaming, is an efficient video streaming protocol that can adapt to network conditions.

I was recently working on a project where I needed to use an HLS format video (the .m3u8 file extension) for a background video: muted, autoplaying, and automatically looping.

Here's how I would normally include that with an .mp4 video…

<video   	muted loop autoplay   	tabindex="-1"  	aria-hidden="true"  	src="https://assets.afcdn.com/video49/20210722/v_645516.m3u8"  >  </video>

But HLS is a live streaming format. As a result, even with the loop attribute, it doesn't automatically loop.

There's no ended event that's fired, because of some weird under-the-hood stuff related to live streams that I don't fully understand.

The fix is to listen for the timeupdate event. This fires every time .currentTime attribute on the <video> element is updated.

Inside, your listener, you can compare the .duration property (which tells you the length of the video) and the .currentTime property (how far along the video is).

If there's less than a second of play time left, you can set the .currenTime attribute to 0, then .play() to the video to loop it back to the beginning.

let video = document.querySelector('video');    // Listen for timeupdate events and restart video if needed  video.addEventListener('timeupdate', function () {  	if (video.duration - video.currentTime > 1) return;  	video.currentTime = 0;  	video.play();  });  

Here's a demo, if you want to see HLS in action.

It also includes the hls.js library required to stream HLS video on the web, and some boilerplate for automatically loading, playing, and looping videos where appropriate.

Like this? A Go Make Things membership is the best way to support my work and help me create more free content.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+ Lintasme

Related Post:

0 Komentar untuk "[Go Make Things] Looping HLS video"

Back To Top