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:
JavaScript
x
12
12
1
const useMyHook = (videoRef: React.MutableRefObject<HTMLVideoElement | null>) => {
2
3
useEffect(() => {
4
const mediaSource = new MediaSource();
5
videoRef.current!.src = URL.createObjectURL(mediaSource);
6
mediaSource.addEventListener('sourceopen', () => {
7
// this never happens
8
});
9
}, []);
10
11
}
12
JavaScript
1
11
11
1
const MyComponent = () => {
2
const videoRef = useRef<HTMLVideoElement | null>(null);
3
const {} = useMyHook(videoRef);
4
5
return (
6
<>
7
<video ref={videoRef} controls />;
8
</>
9
);
10
};
11
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?
Advertisement
Answer
Instantiate and maintain state of MediaSource
throughout the scope of the component:
JavaScript
1
17
17
1
import React, { useState, useEffect, useRef } from 'react'
2
3
const MyComponent = () => {
4
const [mediaSource] = useState(new MediaSource())
5
const videoRef = useRef<HTMLVideoElement | null>(null)
6
7
// component init
8
useEffect(() => {
9
mediaSource.addEventListener('sourceopen', )
10
}, [])
11
12
// videoRef changes
13
useEffect(() => {
14
videoRef?.current!.src = URL.createObjectURL(mediaSource)
15
}, [videoRef])
16
};
17