vue 流式加载mp4文件

video组件 传入assetURL视频地址即可,组件内配置了代理,注意配置/video-api 代理

javascript 复制代码
<template>
  <video @ended="emits(ended)" autoplay muted ref="video">
    <source type="video/mp4" />
    Your browser does not support the video tag.
  </video>
</template>
<script lang="ts" name="Video" setup>
import { onMounted, ref } from 'vue'
const video = ref()
const emits = defineEmits(['ended'])

const props = defineProps<{
  assetURL: string
}>()

const rangeVideo = () => {
  const totalSize = 112702286
  const chunkSize = 1000000
  const numChunks = Math.ceil(totalSize / chunkSize)
  let index = 0
  const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'

  if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
    let mediaSource = new MediaSource()
    video.value.src = URL.createObjectURL(mediaSource)
    mediaSource.addEventListener('sourceopen', sourceOpen)
  } else {
    console.error('Unsupported MIME type or codec: ', mimeCodec)
  }

  function sourceOpen(e) {
    let mediaSource = e.target
    let sourceBuffer = mediaSource.addSourceBuffer(mimeCodec)
    const send = async () => {
      if (index >= numChunks) {
        sourceBuffer.addEventListener('updateend', function (_) {
          mediaSource.endOfStream()
        })
      } else {
        const start = index * chunkSize
        const end = Math.min(start + chunkSize - 1, totalSize - 1)
        fetch('/video-api/' + props.assetURL, {
          headers: {
            Range: `bytes=${start}-${end}`,
            responseType: 'arraybuffer'
          }
        }).then(async (response) => {
          const res = await response.arrayBuffer()
          index++
          sourceBuffer.appendBuffer(res)
          send()
          // video.value.play()
        })
      }
    }
    send()
  }
}

const getRef = () => {
  return video
}

defineExpose({ getRef })

onMounted(() => {
  rangeVideo()
})
</script>
相关推荐
持久的棒棒君4 小时前
npm安装electron下载太慢,导致报错
前端·electron·npm
crary,记忆6 小时前
Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
前端·webpack·angular·angular.js
门前云梦6 小时前
《C语言·源初法典》---C语言基础(上)
c语言·开发语言·学习
漂流瓶jz6 小时前
让数据"流动"起来!Node.js实现流式渲染/流式传输与背后的HTTP原理
前端·javascript·node.js
SamHou06 小时前
手把手 CSS 盒子模型——从零开始的奶奶级 Web 开发教程2
前端·css·web
我不吃饼干7 小时前
从 Vue3 源码中了解你所不知道的 never
前端·typescript
开航母的李大7 小时前
【中间件】Web服务、消息队列、缓存与微服务治理:Nginx、Kafka、Redis、Nacos 详解
前端·redis·nginx·缓存·微服务·kafka
Bruk.Liu7 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio
sjtu_cjs7 小时前
Tensorrt python api 10.11.0笔记
开发语言·笔记·python
哆啦A梦的口袋呀7 小时前
深入理解系统:UML类图
开发语言·python·uml