通过Blob URL使用不同的流更新视频元素src

时间:2019-05-07 23:19:48

标签: reactjs stream video-streaming blob src

我的反应组件“ VideoPlayer”在道具更改时未更新其src属性。

每次调用getUrlStreamForMostRecentMP4OnDb()都会创建一个新的Blob Url对象。该对象流式传输添加到数据库中的最新视频。无论数据库中最新的视频是什么,video元素始终会渲染相同的初始视频。

App.js

import React, { Component } from "react";
import VideoPlayer from "./VideoPlayer";


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

    this.getUrlStreamForMostRecentMP4OnDb = this.getUrlStreamForMostRecentMP4OnDb.bind(
      this
    );

    this.state = {
      playerSource: null,
    };
  }


  async getUrlStreamForMostRecentMP4OnDb() {
    fetch("http://localhost:4000/ytdl/streamMP4")
      .then(re => re.blob())
      .then(blob => URL.createObjectURL(blob))
      .then(url => {
        this.setState({ playerSource: url });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    return (
      <div>
        <button onClick={this.getUrlStreamForMostRecentMP4OnDb}>
          Get url stream for most recent mp4 from db.
        </button>
        {this.state.playerSource ? (
          <VideoPlayer
            key={this.state.playerSource}
            playerSource={this.state.playerSource}
          />
        ) : (
          <div />
        )}
      </div>
    );
  }
}

VideoPlayer.js

import React, { Component } from "react";

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

  render() {
    return (
      <div>
        <video
          id="video"
          width={300}
          ref="player"
          muted={true}
          autoPlay={true}
          loop
          crossOrigin="anonymous"
          src={this.props.playerSource}
        >
        </video>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

我知道这是一个老问题,但我通过像这样直接操作 dom 来解决这个问题:

const onUpload = ({ event, ContentId, ContentIndex }) => {
    if (event.target.files.length) {
        var UploadedVideo = event.target.files[0];

        var MediaUrl = URL.createObjectURL(UploadedVideo);

        var VideoElement = document.getElementById(`video_${ContentId}`);
        if (VideoElement) {
            VideoElement.src = MediaUrl;
            VideoElement.load();
        }
    }
}