如何在reactjs中播放mp4和hls视频?

时间:2017-04-05 13:21:02

标签: reactjs video-streaming html5-video

这是一个普遍的问题,我需要你的专家意见。

我是Reactjs中的新蜜蜂,我有一个要求,我想使用reactjs播放HLS和mp4视频。我有一个直播和录制的网址。

我找到了很多选择。我想要一个单独的播放器作为组件创建并且能够播放hls(.m3u8格式)和mp4视频。

你能不能给我一个更好的方法或一些示例教程?

1 个答案:

答案 0 :(得分:1)

VideoJS是一款功能齐全的HLS播放器,效果非常好,而且

  1. 适用于iOS Safari
  2. 支持playsInline道具以避免在iOS移动设备上全屏显示
  3. 注意:您也可以在iOS上使用自动播放,只要视频开始静音

    首先,您需要在主HTML中添加依赖关系到videojs和HLS插件,如解释in the docs of videojs HLS plugin

    然后,你可以使用如下的反应包装,根据自己的喜好进行修改:

    import React, { PropTypes } from 'react';
    
    export default class VideoPlayer extends Component {
        static propTypes = {
            style: PropTypes.object,
            onVideoEvent: PropTypes.func,
            src: PropTypes.string,
            poster: PropTypes.string
        }
    
        static defaultProps = {
            style: {},
            onVideoEvent: console.log,
            src: '',
            poster: ''
        }
    
        componentDidMount = () => {
            // This is a hack because I don't import video.js as a hard dependency
            // but load it alongside my app bundle
            if (typeof videojs === 'undefined') {
                setTimeout(this.componentDidMount, 500);
                return;
            }
            const { onVideoEvent } = this.props;
            this.player = videojs(this.videoNode);
            const exportEvents = ['timeupdate', 'play', 'playing', 'pause',
                'ended', 'error', 'waiting']; 
            exportEvents.forEach(ev => this.player.on(ev, this.props.onVideoEvent));
        }
    
        componentWillUnmount = () => {
            this.player && this.player.dispose();
            this.player = null;
        }
    
        render = () => (
            <div alt="snap"
                key="media"
                style={ this.props.style }
                data-vjs-player>
    
                <video playsInline
                    className="video-js"
                    preload="auto"
                    poster={ this.props.poster }
                    ref={ r => { this.videoNode = r; } } >
    
                    <source src={ this.props.src } type="application/x-mpegURL" />
    
                </video>
            </div>
        )
    }
    

    Video.js的完整选项和文档,包含播放器的所有自定义和功能can be found here