Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play both mp4 and hls videos in reactjs?

This is a general question i need your expert opinion.

I am a new bee in Reactjs and i have a requirement like ,i want to play both HLS and mp4 videos using reactjs. I have a live streaming and recorded url to play.

I found lot of options to do it. I want a single player which is to be created as a component and able to play hls(.m3u8 format) and mp4 videos.

Could you please suggest me a better way or some sample tutorials?

like image 688
gitu Avatar asked Jan 17 '26 19:01

gitu


1 Answers

VideoJS is a full features HLS player that works pretty well, and

  1. Works in iOS Safari
  2. Support playsInline prop to avoid fullscreen on iOS mobil devices

Note: you can also use autoplay on iOS, as long as the video starts muted

First, you need to add dependencies to videojs and HLS plugin in you main HTML, like explained in the docs of videojs HLS plugin

Then, you can use a react wrapper like below, modify to your own taste:

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>
    )
}

Full options and documentation of Video.js with all customization and capabilities of the player can be found here

like image 149
Pandaiolo Avatar answered Jan 19 '26 19:01

Pandaiolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!