skip to Main Content

I have a HLS encrypted video consisting of a playlist file (namely stream.m3u8) and a key file (namely stream.m3u8.key) and some stream.ts files. I use code below (https://hlsbook.net/playing-hls-video-in-the-browser-part-2/) to play it in a web player and it works fine

<head>
    <link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
    <script src="https://vjs.zencdn.net/7.4.1/video.min.js"></script>
</head>
<body>
    <video id="example-video" class="video-js vjs-default-skin" controls="controls" width="640" height="360">
       <source src="./stream.m3u8" type="application/x-mpegURL" />
    </video>
    <script>
        var player = videojs('example-video');
    </script>
</body>

Now I want to get source file (./stream.m3u8) from an input tag in HTML (instead of the path defined inside code). What I tried is below but it does not work.

<html>
    
    <head>
        <link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
        <script src="https://vjs.zencdn.net/7.4.1/video.min.js"></script>
    </head>
    
    <body>
        <label for="input">Choose a video file to process:</label>
        <input type="file" id="input" name="input_video">
        <video id="video" class="video-js vjs-default-skin" width="320" height="240" controls style="display: none;"></video>
    </body>
    
    <script>
        document.getElementById("input").addEventListener("change", function() {
          var media = URL.createObjectURL(this.files[0]);
          var video = document.getElementById("video");
          video.src = media;
          video.style.display = "block";
          video.play();
        });

        var player = videojs('video');
    </script>

</html>

What is the wrong?

2

Answers


  1. Move the reference to the video element outside the event handler.

    <script>
        var video = document.getElementById("video");
    
        document.getElementById("input").addEventListener("change", function() {
          var media = URL.createObjectURL(this.files[0]);
          video.src = media;
          video.style.display = "block";
          video.play();
        });
    
        var player = videojs('video');
    </script>
    
    Login or Signup to reply.
  2. I have tried with your code and find the problem: video id changed
    the id for video tag changed

    So, you have to change this line in your code too

    var video = document.getElementById("video_html5_api");
    

    edit:
    the anwser that putting var video = document.getElementById("video"); outside the listener work fine too

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search