acrazing
acrazing

Reputation: 2284

How to get hls video width/height in javascript?

I use video tag to play HLS video, and the video size is 0 always.

<video id=video src="http://xxx.m3u8" autoplay controls/>
<script>
    const video = document.getElementById('video')
    video.addEventListener('play', () => {
        console.log(video.videoWidth, video.videoHeight)
        // both are 0
    })
</script>

Upvotes: 2

Views: 3223

Answers (2)

Nasib
Nasib

Reputation: 1559

"loadedmetadata" wont' work for HLS streams,
so this is the best solution

var video = document.getElementById("video")
video.onplaying = function () {
    var width = video.videoWidth
    var height = video.videoHeight
    console.log("video dimens loaded w="+width+" h="+height)
    }

Upvotes: 1

jolumg
jolumg

Reputation: 744

Currently desktop browsers do not support playing an HLS video directly using just the video tag. (Maybe it does work on Safari or IOS).

To reproduce an HLS stream you need to use one of the video players available. You have some open source projects, like hlsjs: https://github.com/video-dev/hls.js. Or comercial players like flowplayer, or jwplayer.

Basic html code using hlsjs player:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  if(Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
</script>

Upvotes: 1

Related Questions