视频的分片的后端代码可以参考前一篇文章,前端部分也基本上差不多,详细的解释也在前文
图片文件的分片加载实现,前后端代码, fetch + koa2
上代码:
const rangeVideo = () => {
const totalSize = 1397956
const chunkSize = 500000
const numChunks = Math.ceil(totalSize / chunkSize)
let chunk = new Blob()
let index = 0
send()
function send() {
if (index >= numChunks) return
const start = index * chunkSize
const end = Math.min(start + chunkSize - 1, totalSize - 1)
fetch('Videourl', {
headers: { Range: `bytes=${start}-${end}` },
})
.then((response) => {
index++
return response.blob()
})
.then((blob) => {
send()
chunk = new Blob([chunk, blob], { type: 'video/mp4' })
const url = URL.createObjectURL(chunk)
const currentTime = video.currentTime
video.src = url
video.currentTime = currentTime
video.play()
})
}
}```
- 这里有一个缺点,就是每次重新设置src的时候,视频画面会闪动一下,体验不是很好,有待优化