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>
相关推荐
遇见你...1 小时前
TypeScript
前端·javascript·typescript
Highcharts.js1 小时前
Highcharts Grid 中文站正式上线:表格数据处理的全新选择
前端·javascript·数据库·表格数据·highcharts·可视化图表·企业级图表
阿正的梦工坊4 小时前
JavaScript 微任务与宏任务完全指南
开发语言·javascript·ecmascript
懂懂tty4 小时前
CRA 迁移 Rspack(实战)
前端·架构
知行合一。。。5 小时前
Python--05--面向对象(属性,方法)
android·开发语言·python
青梅橘子皮5 小时前
C语言---指针的应用以及一些面试题
c语言·开发语言·算法
浅时光_c5 小时前
3 shell脚本编程
linux·开发语言·bash
小码哥_常5 小时前
Kotlin 助力 Android 启动“大提速”
前端
Evand J5 小时前
【三维轨迹目标定位,CKF+RTS,MATLAB程序】基于CKF与RTS平滑的三维非线性目标跟踪(距离+方位角+俯仰角)
开发语言·matlab·目标跟踪
GreenTea6 小时前
AI 时代,工程师的不可替代性在哪里
前端·人工智能·后端