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>
相关推荐
编码浪子2 小时前
趣味学RUST基础篇(智能指针_结束)
开发语言·算法·rust
CVer儿3 小时前
qt资料2025
开发语言·qt
BillKu3 小时前
Vue3 + Element-Plus 抽屉关闭按钮居中
前端·javascript·vue.js
DevilSeagull3 小时前
JavaScript WebAPI 指南
java·开发语言·javascript·html·ecmascript·html5
2zcode3 小时前
基于Matlab不同作战类型下兵力动力学模型的构建与稳定性分析
开发语言·matlab
面向星辰3 小时前
html中css的四种定位方式
前端·css·html
Async Cipher4 小时前
CSS 权重(优先级规则)
前端·css
大怪v4 小时前
前端佬:机器学习?我也会啊!😎😎😎手“摸”手教你做个”自动驾驶“~
前端·javascript·机器学习
Liquad Li4 小时前
Angular 面试题及详细答案
前端·angular·angular.js
用户21411832636025 小时前
首发!即梦 4.0 接口开发全攻略:AI 辅助零代码实现,开源 + Docker 部署,小白也能上手
前端