javascriptreactjsmedia-source

MediaSource never emit sourceopen event in React


I'm trying to stream a video file using Javascript's MediaSource API in a React custom hook.

Here's the snippet of my code:

const useMyHook = (videoRef: React.MutableRefObject<HTMLVideoElement | null>) => {
...
  useEffect(() => {
    const mediaSource = new MediaSource();
    videoRef.current!.src = URL.createObjectURL(mediaSource);
    mediaSource.addEventListener('sourceopen', () => {
      // this never happens
    });
  }, []);
...
}
const MyComponent = () => {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const {} = useMyHook(videoRef);

  return (
    <>
      <video ref={videoRef} controls />;
    </>
  );
};

It looks like mediaSource never emit 'sourceopen' event.

What more, when I'm trying to use this code in different project with simple html and javascript it works fine.

I was trying to use document.getElementByTagName instead of useRef or use this directly in my component, but with the same result.

Can somebody tell me what is the problem? Is there any problem with React or something?


Solution

  • Instantiate and maintain state of MediaSource throughout the scope of the component:

    import React, { useState, useEffect, useRef } from 'react'
    
    const MyComponent = () => {
      const [mediaSource] = useState(new MediaSource())
      const videoRef = useRef<HTMLVideoElement | null>(null)
    
      // component init
      useEffect(() => {
        mediaSource.addEventListener('sourceopen', ...)
      }, [])
    
      // videoRef changes
      useEffect(() => {
        videoRef?.current!.src = URL.createObjectURL(mediaSource)
      }, [videoRef])
    };