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>
相关推荐
泯泷34 分钟前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花34 分钟前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷34 分钟前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜36 分钟前
Spring Boot 核心知识点总结
前端
lichenyang4531 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕1 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js
朦胧之1 小时前
页面白屏卡住排查方法
前端·javascript
用户593608741401 小时前
Playwright 黑魔法:用 ClipboardEvent 绕过 React 富文本编辑器
前端
石山岭2 小时前
自己动手写了一个 Android 虚拟定位 App:GPSSimulate 技术实
android·前端
犇驫聊AI2 小时前
Chrome DevTools MCP + Claude Code 自定义skills生成接口代码生成器
前端·javascript