【问题标题】:Updating video element src with different streams via blob URL通过 blob URL 使用不同的流更新视频元素 src
【发布时间】:2019-09-25 15:32:43
【问题描述】:

我的反应组件 'VideoPlayer' 不会在其 props 更改时更新其 src 属性。

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

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

【问题讨论】:

标签: reactjs stream video-streaming blob src


【解决方案1】:

我知道这是一个老问题,但我通过像这样直接操作 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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 2020-09-19
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多