【问题标题】:How to play both mp4 and hls videos in reactjs?如何在 reactjs 中同时播放 mp4 和 hls 视频?
【发布时间】:2017-08-31 03:28:17
【问题描述】:

这是一个一般性问题,我需要您的专家意见。

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

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

您能否建议我一个更好的方法或一些示例教程?

【问题讨论】:

  • react 仍然是 html5 常用的 javascript,我认为创建支持播放列表的视频组件没有问题。另外我敢打赌,已经有很多这样的组件了。
  • 无耻推广我的 npm 包:npmjs.com/package/react-jplayer 两种格式都支持,虽然它还不支持播放列表。演示react-jplayer.azurewebsites.net
  • 我正在使用 videojs 加上 hls 插件,包装在一个反应​​组件中。适用于 mp4 和 hls 播放列表、自适应流媒体等。编辑:它适用于 ios safari,并且可以使用 playsInline 元素上的 playsInline 道具内联播放,这对于免费播放器来说有点难以实现。

标签: reactjs video-streaming html5-video


【解决方案1】:

VideoJS 是一个功能齐全的 HLS 播放器,运行良好,并且

  1. 适用于 iOS Safari
  2. 支持playsInline prop 避免在 iOS 移动设备上全屏

注意:你也可以在 iOS 上使用自动播放,只要视频开始静音

首先,您需要在主 HTML 中添加对 videojs 和 HLS 插件的依赖项,如 in the docs of videojs HLS plugin 解释的那样

然后,您可以使用如下所示的 react 包装器,根据自己的喜好进行修改:

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

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 2014-06-05
    • 2013-12-26
    • 2017-04-07
    • 1970-01-01
    • 2019-12-14
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多