Search code examples
javascriptvideo.jsmediastream

Get MediaStream from a live videojs hls streaming


I've got this live streaming playing on a videojs player :

<video-js id="video-player" class="vjs-default-skin" controls preload="auto" width="640" height="268">
    <source src="https://******.com:****/visio/streaming_30099/playlist.m3u8" type="application/x-mpegURL">
</video-js>

I want to extract the video track from this live streaming and publish it via a WebRTC peer connection.

I know I could get a media stream from a canvas element "copying" the video-player but is there a more direct way like :

var stream = document.getElementById('video-player').srcObject; // but srcObject = null :(
var videoTrack = stream.getVideoTracks()[0];
...

Let me know if I'm not clear enough. Thanks !


Solution

  • I was referring in my question to the canvas element captureStream() method that return a MediaStream, well this method exists also for HTMLMediaElement (video or audio player).

    See https://w3c.github.io/mediacapture-fromelement/#html-media-element-media-capture-extensions :

    1. HTML Media Element Media Capture Extensions

    The method captureStream is added on HTML [HTML5] media elements. Methods for capture are added to both HTMLMediaElement and HTMLCanvasElement.

    Both MediaStream and HTMLMediaElement expose the concept of a track. Since there is no common type used for HTMLMediaElement, this document uses the term track to refer to either VideoTrack or AudioTrack. MediaStreamTrack is used to identify the media in a MediaStream.

    So my code became :

    <video id="video-player" class="video-js vjs-default-skin vjs-16-9" controls preload="auto" width="640" height="268">
       <source src="https://xxxxx.com/visio/streaming_30099/playlist.m3u8" type="application/x-mpegURL">
    </video>
    
    <script>
    const videoPlayer = document.getElementById('video-player').getElementsByTagName('video')[0]; // VideoJS will turn your video element into a div and add a its own video element as a child
    const stream = videoPlayer.captureStream();
    </script>