简体   繁体   English

使用 MediaSource 在 React 组件中流式传输视频文件

[英]Using MediaSource to stream a video file in a React component

I'm trying to stream a video file using Javascript's MediaSource API in a React component.我正在尝试在 React 组件中使用 Javascript 的 MediaSource API 流式传输视频文件。

Here's my component:这是我的组件:

const RawPlayer: React.FC= () => {
    const videoRef = useRef<HTMLVideoElement>(null);


    useEffect(() => {
        const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';

        if (videoRef.current && MediaSource.isTypeSupported(mimeCodec)) {
            const myMediaSource = new MediaSource();
            const url = URL.createObjectURL(myMediaSource);

            videoRef.current.src = url;

            myMediaSource.addEventListener('sourceopen', () => {
                const videoSourceBuffer = myMediaSource.addSourceBuffer(mimeCodec);

                videoSourceBuffer.addEventListener('error', console.log);

                // this is just an express route that return an mp4 file using `res.sendFile`
                fetch('http://localhost:3001/video/bC4Zud78/raw').then((response) => {
                    return response.arrayBuffer();
                }).then((videoData) => {
                    videoSourceBuffer.appendBuffer(videoData);
                });
            });
        }
    });

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

Strangely it doesn't work.奇怪的是它不起作用。 When I go on the page, there's a spinner on the video, the spinner disappear then nothing happens.当我进入页面时,视频上有一个微调器,微调器消失然后什么也没有发生。

This error listener:此错误侦听器:

videoSourceBuffer.addEventListener('error', console.log);

Log this:记录这个:

Which is not really an error.这不是一个真正的错误。


Here's a reproduction: https://github.com/AnatoleLucet/react-MediaSource这是复制品: https : //github.com/AnatoleLucet/react-MediaSource

The code is in src/App.tsx代码在src/App.tsx

The issue was the file format I recieve from the api.问题是我从 api 收到的文件格式。 If I try with this file in my fetch it works perfectly!如果我在我的fetch尝试使用这个文件,它会完美运行!

A note on the file format: I struggled with this as well.关于文件格式的说明:我也遇到了这个问题。 The mp4 has to be fragmented for it to work with MediaSource (in my tests, please offer any corrections). mp4 必须被分段才能与 MediaSource 一起使用(在我的测试中,请提供任何更正)。 You can use this utility to create a fragmented mp4 from an unfragmented one:您可以使用此实用程序从未分段的 mp4 中创建分段的 mp4:

https://www.bento4.com/documentation/mp4fragment/ https://www.bento4.com/documentation/mp4fragment/

For a full list of valid mime codecs, see:有关有效 mime 编解码器的完整列表,请参阅:

https://cconcolato.github.io/media-mime-support/ https://cconcolato.github.io/media-mime-support/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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