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>
相关推荐
Lossya几秒前
【python实操】python小程序之过七游戏以及单词单复数分类
开发语言·python·游戏·小程序
心易行者2 分钟前
Python 绘图艺术:解锁数据故事的三把密钥
开发语言·python·信息可视化
万物皆可Hook5 分钟前
咸鱼sign逆向分析与爬虫实现
javascript·爬虫·python·算法
Clank的游戏栈6 分钟前
Unity3D Compute Shader同步详解
java·开发语言·算法
丶重明12 分钟前
【2024】前端学习笔记11-网页布局-弹性布局flex
前端·笔记·学习
枫心18319 分钟前
Python基础语句教学
开发语言·python
清风~徐~来23 分钟前
【C++标准模版库】map和set的介绍及使用
开发语言·c++
是小恐龙啊26 分钟前
动态顺序表的增删改查(数据结构)
c语言·开发语言·数据结构·算法
2401_8582861135 分钟前
E36.C语言模拟试卷1第一大题选题解析与提示(未完)
c语言·开发语言
计算机程序设计开发1 小时前
基于小程序+Vue + Spring Boot的进销存库存出库入库统计分析管理系统
前端·vue.js·spring boot·课程设计·计算机毕设·计算机毕业设计