Player

Player is the root component of the Video-React player. All the others components should be in this component.

Attributes

All the attributes for the Player component, they can be added as React properties.

NameTypeDefaultDescription
fluidbooltrueIn fluid mode, it’s 100% wide all the time, the height will be calculated by the video's ratio.
widthnumber-The width value of video, could be an number or percent or auto. (This attribute is effective only if you set fluid as false)
heightnumber-The height value of video, could be an number or percent or auto. (This attribute is effective only if you set fluid as false)
srcstring-The URL of the video to embed. This is optional; you may instead use the <source> element within the Player block to specify the video to embed.
posterstring-A URL indicating a poster frame to show until the user plays or seeks. If this attribute isn't specified, nothing is displayed until the first frame is available; then the first frame is shown as the poster frame.
preloadenum-This enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience. It may have one of the following values:
  • none: indicates that the video should not be preloaded.
  • metadata: indicates that only video metadata (e.g. length) is fetched.
  • auto: indicates that the whole video file could be downloaded, even if the user is not expected to use it.
  • the empty string: synonym of the auto value.
mutedboolfalseA Boolean attribute which indicates the default setting of the audio contained in the video. If set, the audio will be initially silenced. Its default value is false, meaning that the audio will be played when the video is played.
playsInlineboolfalse[iOS only]Determines whether HTML5 videos play inline or use the native full-screen controller.
aspectRatiostringautoThe aspect ratio is the width of the video divided by its height. Posible values: auto, 16:9, 4:3, etc.
autoPlayboolfalseif specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data.
startTimenumber-Seek the Video at A Specific Time On Load

Properties

NameDescription
playbackRateSets or returns the speed of the video playback. For example:
<Player ref={(player) => { this.player = player }}>
  <source src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4" />
</Player>

// access the player object by ref (this.player)
// set playbackRate to 2
this.player.playbackRate = 2; 
mutedSets or returns whether the video is muted or not
volumeSets or returns the volume of the video
videoWidthReturns the width of the video
videoHeightReturns the height of the video
videoReturns the Video component object

Methods

The Player component has some methods to control the video and the player.

NameDescription
getState()Get the redux State. For example:
const { player } = this.player.getState();
console.log(player.currentTime); // print current time
play()Play the video.
pause()Pause the video.
load()Change the video source and re-load the video
addTextTrack()Add a new text track to the video
canPlayType()Check if your browser can play different types of video:
seek(time)Seek video by time (seconds)
forward(seconds)Jump forward x seconds
replay(seconds)Jump back x seconds
toggleFullscreen()Enter or exist full screen
subscribeToStateChange(listener)Subscribe to the player state changes.
componentDidMount() {
  // subscribe state change
  this.player.subscribeToStateChange(this.handleStateChange.bind(this));
}

handleStateChange(state, prevState) {
  // copy player state to this component's state
  this.setState({
    player: state,
    currentTime: state.currentTime
  });
}

State

We use redux to manage the player state. Using getState method can get the state object. This is the list of all the states.

NameDescription
playerThe player state includes all the states about the video and the player. Below is the properties list of the player state.
 currentSrcReturns the URL of the current video
 durationReturns the length of the current video (in seconds)
 currentTimeReturns the current playback position in the video (in seconds)
 seekingTimeReturns the current seeking position in the video (in seconds)
 bufferedReturns a TimeRanges object representing the buffered parts of the video
 waitingReturns whether the player needs to buffer the next frame
 seekingReturns whether the user is currently seeking in the video
 pausedReturns whether the player has been paused
 autoPausedReturns whether the player has been paused by the player itself
 endedReturns whether the playback of the video has ended or not
 playbackRateReturns the speed of the video playback
 mutedReturns whether the video is muted or not
 volumeReturns the volume of the video.
 readyStateReturns the current ready state of the video
 networkStateReturns the current network state of the video
 videoWidthReturns the volume of the video
 videoHeightReturns the height of the video
 hasStartedReturns whether the video has been started
 userActivityReturns whether the user is in activity.
 isActiveReturns whether the player is in activity.
 isFullscreenReturns whether the player is in fullscreen.
 videoIdSet the id of the video element.

Examples

Some examples to show how to use the player.

Control the player

This is an example on how to control the player from outside the component.

Current Time 0:00
/
Duration Time 0:00
Progress: NaN%
State
import React, { Component } from 'react';
import { PrismCode } from 'react-prism';
import { Player, ControlBar } from 'video-react';
import { Button } from 'reactstrap';

const sources = {
  sintelTrailer: 'http://media.w3.org/2010/05/sintel/trailer.mp4',
  bunnyTrailer: 'http://media.w3.org/2010/05/bunny/trailer.mp4',
  bunnyMovie: 'http://media.w3.org/2010/05/bunny/movie.mp4',
  test: 'http://media.w3.org/2010/05/video/movie_300.webm'
};

export default class PlayerControlExample extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      source: sources.bunnyMovie
    };

    this.play = this.play.bind(this);
    this.pause = this.pause.bind(this);
    this.load = this.load.bind(this);
    this.changeCurrentTime = this.changeCurrentTime.bind(this);
    this.seek = this.seek.bind(this);
    this.changePlaybackRateRate = this.changePlaybackRateRate.bind(this);
    this.changeVolume = this.changeVolume.bind(this);
    this.setMuted = this.setMuted.bind(this);
  }

  componentDidMount() {
    // subscribe state change
    this.player.subscribeToStateChange(this.handleStateChange.bind(this));
  }

  setMuted(muted) {
    return () => {
      this.player.muted = muted;
    };
  }

  handleStateChange(state) {
    // copy player state to this component's state
    this.setState({
      player: state
    });
  }

  play() {
    this.player.play();
  }

  pause() {
    this.player.pause();
  }

  load() {
    this.player.load();
  }

  changeCurrentTime(seconds) {
    return () => {
      const { player } = this.player.getState();
      this.player.seek(player.currentTime + seconds);
    };
  }

  seek(seconds) {
    return () => {
      this.player.seek(seconds);
    };
  }

  changePlaybackRateRate(steps) {
    return () => {
      const { player } = this.player.getState();
      this.player.playbackRate = player.playbackRate + steps;
    };
  }

  changeVolume(steps) {
    return () => {
      const { player } = this.player.getState();
      this.player.volume = player.volume + steps;
    };
  }

  changeSource(name) {
    return () => {
      this.setState({
        source: sources[name]
      });
      this.player.load();
    };
  }

  render() {
    return (
      <div>
        <Player
          ref={player => {
            this.player = player;
          }}
          autoPlay
        >
          <source src={this.state.source} />
          <ControlBar autoHide={false} />
        </Player>
        <div className="py-3">
          <Button onClick={this.play} className="mr-3">
            play()
          </Button>
          <Button onClick={this.pause} className="mr-3">
            pause()
          </Button>
          <Button onClick={this.load} className="mr-3">
            load()
          </Button>
        </div>
        <div className="pb-3">
          <Button onClick={this.changeCurrentTime(10)} className="mr-3">
            currentTime += 10
          </Button>
          <Button onClick={this.changeCurrentTime(-10)} className="mr-3">
            currentTime -= 10
          </Button>
          <Button onClick={this.seek(50)} className="mr-3">
            currentTime = 50
          </Button>
        </div>
        <div className="pb-3">
          <Button onClick={this.changePlaybackRateRate(1)} className="mr-3">
            playbackRate++
          </Button>
          <Button onClick={this.changePlaybackRateRate(-1)} className="mr-3">
            playbackRate--
          </Button>
          <Button onClick={this.changePlaybackRateRate(0.1)} className="mr-3">
            playbackRate+=0.1
          </Button>
          <Button onClick={this.changePlaybackRateRate(-0.1)} className="mr-3">
            playbackRate-=0.1
          </Button>
        </div>
        <div className="pb-3">
          <Button onClick={this.changeVolume(0.1)} className="mr-3">
            volume+=0.1
          </Button>
          <Button onClick={this.changeVolume(-0.1)} className="mr-3">
            volume-=0.1
          </Button>
          <Button onClick={this.setMuted(true)} className="mr-3">
            muted=true
          </Button>
          <Button onClick={this.setMuted(false)} className="mr-3">
            muted=false
          </Button>
        </div>
        <div className="pb-3">
          <Button onClick={this.changeSource('sintelTrailer')} className="mr-3">
            Sintel teaser
          </Button>
          <Button onClick={this.changeSource('bunnyTrailer')} className="mr-3">
            Bunny trailer
          </Button>
          <Button onClick={this.changeSource('bunnyMovie')} className="mr-3">
            Bunny movie
          </Button>
          <Button onClick={this.changeSource('test')} className="mr-3">
            Test movie
          </Button>
        </div>
        <div>State</div>
        <pre>
          <PrismCode className="language-json">
            {JSON.stringify(this.state.player, null, 2)}
          </PrismCode>
        </pre>
      </div>
    );
  }
}
Change the player url

This is an example on how to change the video url.

Current Time 0:00
/
Duration Time 0:00
Progress: NaN%
import React, { Component } from 'react';
import { Player } from 'video-react';
import { Button, Form, FormGroup, Label, Input } from 'reactstrap';

export default class PlayerExample extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      playerSource: 'https://media.w3.org/2010/05/sintel/trailer_hd.mp4',
      inputVideoUrl: 'http://www.w3schools.com/html/mov_bbb.mp4'
    };

    this.handleValueChange = this.handleValueChange.bind(this);
    this.updatePlayerInfo = this.updatePlayerInfo.bind(this);
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.playerSource !== prevState.playerSource) {
      this.player.load();
    }
  }

  handleValueChange(e) {
    const { value } = e.target;
    this.setState({
      inputVideoUrl: value
    });
  }

  updatePlayerInfo() {
    const { inputVideoUrl } = this.state;
    this.setState({
      playerSource: inputVideoUrl
    });
  }

  render() {
    return (
      <div>
        <Player
          ref={player => {
            this.player = player;
          }}
          videoId="video-1"
        >
          <source src={this.state.playerSource} />
        </Player>
        <div className="docs-example">
          <Form>
            <FormGroup>
              <Label for="inputVideoUrl">Video Url</Label>
              <Input
                name="inputVideoUrl"
                id="inputVideoUrl"
                value={this.state.inputVideoUrl}
                onChange={this.handleValueChange}
              />
            </FormGroup>
            <FormGroup>
              <Button type="button" onClick={this.updatePlayerInfo}>
                Update
              </Button>
            </FormGroup>
          </Form>
        </div>
      </div>
    );
  }
}