如何将 hls.js 与 React 结合使用

2024-05-15

我需要一些帮助来尝试弄清楚如何在 React 中使用 hls.js。 让我解释一下我必须从 api 获取 m3u8 的情况我能够使用基本的 html 使其工作<script>标签,但当我尝试在 React 上实现它时,它不起作用,感谢任何帮助。这是我到目前为止所得到的:

import React, { Component } from "react";

import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import ButtonBase from "@material-ui/core/ButtonBase";
import CircularProgress from "@material-ui/core/CircularProgress";

import Hls from "hls.js";

const styles = theme => ({
  root: {
    flexGrow: 1,
    paddingTop: theme.spacing.unit * 2,
    paddingBottom: theme.spacing.unit * 2,
    marginBottom: 24,
    marginLeft: 24,
    marginRight: 60
  },
  image: {
    marginLeft: 24,
    width: 200,
    height: 200
  },
  img: {
    display: "block",
    width: 200,
    height: 200,
    maxWidth: "100%",
    maxHeight: "100%"
  },
  detail: {
    marginLeft: 16
  },
  progress: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center"
  }
});

class Video extends Component {
  constructor(props) {
    super(props);
  }

  componentWillReceiveProps(props) {
    if (props.episode && this.player) {
      var hlsUrl = props.episode.assets.hls;
      var video = this.player;
      if (video.canPlayType("application/vnd.apple.mpegurl")) {
        // If HLS is natively supported, let the browser do the work!
        video.src = "hlsUrl";
        video.addEventListener("loadedmetadata", function() {
          video.play();
        });
      } else if (Hls.isSupported()) {
        // If the browser supports MSE, use hls.js to play the video
        var hls = new Hls({
          // This configuration is required to insure that only the
          // viewer can access the content by sending a session cookie
          // to api.video service
          xhrSetup: function(xhr, url) {
            xhr.withCredentials = true;
          }
        });
        hls.loadSource(hlsUrl);
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, function() {
          video.play();
        });
      } else {
        alert("Please use a modern browser to play the video");
      }
    }
  }

  handleSerieClick = () => {
    this.props.history.push("/" + this.props.serie.apiName);
  };

  _onTouchInsidePlayer() {
    if (this.player.paused) {
      this.player.play();
    } else {
      this.player.pause();
    }
  }

  render() {
    const { classes, theme } = this.props;
    if (this.props.episode) {
      const { assets, title, description, videoId } = this.props.episode;
      return (
        <Grid className={classes.root} item xs={12}>
          <video
            controls
            onClick={this._onTouchInsidePlayer}
            ref={player => (this.player = player)}
            autoPlay={true}
          />
        </Grid>
      );
    } else {
      return (
        <Grid className={classes.progress} item xs={12}>
          <CircularProgress size={100} />
        </Grid>
      );
    }
  }
}

export default withStyles(styles, { withTheme: true })(Video);

这是适用于的代码<script> tag

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

<video id="video"></video>

<script>
  var hlsUrl = 'https://cdn.libcast.net/stream/3de8ff01-18f7-4262-a1f2-abeeb9bb962b/hls/manifest.hls';
  var video = document.getElementById('video');
  if (video.canPlayType('application/vnd.apple.mpegurl')) {
    // If HLS is natively supported, let the browser do the work!
    video.src = 'hlsUrl';
    video.addEventListener('loadedmetadata',function() {
      video.play();
    });

  } else if (Hls.isSupported()) {
    // If the browser supports MSE, use hls.js to play the video
    var hls = new Hls({
      // This configuration is required to insure that only the 
      // viewer can access the content by sending a session cookie
      // to api.video service
      xhrSetup: function(xhr, url) { xhr.withCredentials = true; }
    });
    hls.loadSource(hlsUrl);
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
    });

  } else {
    alert('Please use a modern browser to play the video');
  }
</script>

我从 props 中的父组件传递 hls 源,在 componentWillRecieveProps 中我尝试使用源来运行播放器

EDIT

问题似乎是<video>当我尝试应用源时,标记未定义。


正在初始化 hlscomponentWillReceiveProps可能是“太早了”。参考是在渲染执行期间创建的,因此您的this.video可能是null当时。

尝试将你的逻辑转移到componentDidMount(如果你从一开始就传递了适当的道具)或者至少componentDidUpdate.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 hls.js 与 React 结合使用 的相关文章

随机推荐

  • 如何对我的自定义验证属性进行单元测试

    我有一个自定义的 asp net mvc 类验证属性 我的问题是如何对其进行单元测试 测试类是否具有该属性是一回事 但这实际上并不能测试其中的逻辑 这就是我想测试的 Serializable EligabilityStudentDebtsA
  • 删除向量类成员

    我有一个 A 类 其成员是另一个 B 类的对象指针向量 class A std vector
  • 在下载整个文件之前是否可以知道 MP3 的持续时间?

    这是一个关于MP3文件格式的问题 我一直在寻找一种获得 MP3 持续时间的方法 由于我使用 JLayer SPI 来解码 MP3 我发现在音频源是文件的情况下这是可能的 AudioFileFormat fileFormat AudioSys
  • 如何检查 $row['column_name'] 是否返回空 php mysql

    我有一个带有列的表格 id name phone describe 当我从这个表中获取值时 我正在使用 row mysql fetch array query 现在我想检查是否 row describe 返回空值 如何查看php 您可以使用
  • 在 Clearcase 上使用 Mercurial 时保留历史记录

    我在 ClearCase 商店工作 CC 在集成团队的工作方面做得很好 尽管我们的代码审查流程阻止我使用它来跟踪我的日常更改 在我的 CC 视图之上创建 hg 存储库效果非常好 我可以跟踪我的更改并轻松在文件服务器上进行备份 为人们生成差异
  • 多种语言的多种字体

    我最近在开发应用程序时遇到了一种情况 我必须在文本视图中显示不同的语言 目前我正在展示一些使用字体 字体像这样 Typeface tf Typeface createFromAsset this getAssets DroidHindi t
  • Rails:CSRF 令牌不工作但已设置

    我在 Heroku 上有我的 Rails 3 应用程序 当我发送银行信息时 我得到 WARNING Can t verify CSRF token authenticity但我的 CSRF 令牌已设置 https gist github c
  • 两个整数乘积的模

    我必须找到c c a b mod m a b c m 是 32 位整数 但 a b 可以超过 32 位 我正在尝试找出一种计算 c 的方法 而不使用 long 或任何 gt 32 位的数据类型 有任何想法吗 如果m是质数 事情可以简化吗 注
  • 用 C++ 生成 AST

    我正在用 C 制作一个解释器 到目前为止我已经有了词法分析器来生成标记 问题是我不确定如何生成 行走 解析树 我正在考虑使用数组数组来制作解析树 但我不确定如何以正确的顺序将标记实际插入到解析树中 我不确定是自上而下 左右还是自下而上 左右
  • Quarkus / CDI 和“java config”DI 定义

    我刚刚开始 quarkus 概念验证 容器启动时间太棒了 现在 我正在研究依赖注入部分 并找出选项 https quarkus io blog quarkus dependency injection https quarkus io bl
  • 为什么可以更改 const char* 变量的值?

    为什么下面的 C 代码可以工作 const char str NULL str test str test2 既然str是一个指向常量字符的指针 为什么我们可以给它分配不同的字符串文字呢 此外 我们如何保护str不被修改呢 例如 如果我们后
  • 没有端点在 net.pipe://localhost/ 上监听

    我有两个 WCF 服务托管在 Windows Server 2003 计算机上的单个 Windows 服务中 如果 Windows 服务需要访问任一 WCF 服务 例如发生定时事件时 它将使用公开的五个命名管道端点之一 不同的服务协定 该服
  • 如何使用 winforms 在 vb.net 中制作大型按钮网格(24x20 或类似)?

    我正在 vb net WinForms 中制作一个座位预订系统 我需要用户能够选择他们想要使用的座位并改变颜色 这样他们就可以知道它已选择 我开始尝试使用按钮 但 480 个按钮严重减慢了表单的加载时间 然后我尝试了在行 列中带有按钮的数据
  • onclick 函数上的 CSS 选择器

    有没有办法让CSS选择器onclick function 您可以在onclick https stackoverflow com questions 24365416 select element which have specific a
  • 快速约会算法

    我在一家咨询公司工作 大部分时间都在客户所在地 正因为如此 我很少见到同事 为了更好地了解彼此 我们将安排一个晚宴 会有很多小桌子 方便人们聊天 为了在聚会期间与尽可能多的不同的人交谈 每个人都必须每隔一段时间 比如每小时 换一张桌子 如何
  • Python:使用 string.format() 将单词大写

    是否可以使用字符串格式将单词大写 例如 user did such and such format user foobar 应该返回 Foobar 做了这样那样的事情 请注意 我很清楚 capitalize 但是 这是我正在使用的代码 非常
  • 通过推送通知唤醒

    Suppose 有一些对象 例如 一个数组a 和依赖于对象的条件 例如 a empty 当前线程以外的某些线程可以操作该对象 a 因此条件评估值的真实性会随着时间的推移而变化 如何让当前线程在代码中的某个时刻休眠 并在条件满足时通过推送通知
  • 片段内容下方是否存在持久性 BottomSheet?

    Using a 持久底表 https material google com components bottom sheets html bottom sheets persistent bottom sheets 在一个协调器布局 htt
  • CakePHP 会话被写入 /tmp/ 而不是 /app/tmp/sessions/

    这里有类似的简单但未回答的问题 cakephp 会话 tmp sessions 中没有新文件 https stackoverflow com questions 24733151 cakephp session no new files i
  • 如何将 hls.js 与 React 结合使用

    我需要一些帮助来尝试弄清楚如何在 React 中使用 hls js 让我解释一下我必须从 api 获取 m3u8 的情况我能够使用基本的 html 使其工作