简体   繁体   中英

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 is 0
    })
</script>

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>

"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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM