react18 + ts 使用video.js 直播.m3u8格式的视频流

一、安装依赖

我使用的video.js版本是8.17.3,从 Video.js 7.x 开始,HLS 支持被内置到了 Video.js 中所以不需要安装其他依赖

复制代码
npm i video.js 

二、创建VideoPlayer组件

复制代码
import React, { useEffect, useRef } from 'react'
import videojs from 'video.js'
import 'video.js/dist/video-js.css' // 引入 Video.js 样式
import Player from 'video.js/dist/types/player'

interface Props {
  src: string // HLS 流的 URL
}

const VideoPlayer: React.FC<Props> = ({ src }) => {
  const playerRef = useRef<Player>()
  useEffect(() => {
    // 初始化 Video.js 播放器
    playerRef.current = videojs('my-player', {
      controls: true,
      preload: 'auto',
      sources: [
        {
          src: src,
          type: 'application/x-mpegURL', // HLS MIME 类型
        },
      ],
    })

    // 清理函数
    return () => {
      if (playerRef.current) {
        playerRef.current.dispose()
      }
    }
  }, [src])

  return (
    <div>
      <video id="my-player" className="video-js vjs-default-skin"></video>
    </div>
  )
}

export default VideoPlayer

三、使用VideoPlayer组件

复制代码
// App.tsx
import React from 'react';
import VideoPlayer from './VideoPlayer';

function App() {
  return (
    <div className="App">
      <VideoPlayer />
    </div>
  );
}

export default App;
相关推荐
余人于RenYu4 小时前
Claude + Figma MCP
前端·ui·ai·figma
杨艺韬7 小时前
vite内核解析-第2章 架构总览
前端·vite
我是伪码农7 小时前
外卖餐具智能推荐
linux·服务器·前端
2401_885885048 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
小李子呢02118 小时前
前端八股性能优化(2)---回流(重排)和重绘
前端·javascript
程序员buddha8 小时前
深入理解ES6 Promise
前端·ecmascript·es6
吴声子夜歌8 小时前
ES6——Module详解
前端·ecmascript·es6
剪刀石头布啊9 小时前
原生form发起表单干了啥
前端
剪刀石头布啊9 小时前
表单校验场景,如何实现页面滚动到报错位置
前端
gyx_这个杀手不太冷静9 小时前
大人工智能时代下前端界面全新开发模式的思考(二)
前端·架构·ai编程