需求及问题
对用户本地上传的视频进行预览播放,然后做一些操作(裁剪、添加滤镜等)。 但是,浏览器(chrome)只能对编码为h264的视频进行预览,对于浏览器不能预览的视频,前端需要调用后端接口上传视频并转码。 问题是:如何判断浏览器能不能播放当前视频
最初思路
最开始的思路是判断视频文件的编码,如果是h264,则认为可以播放,但是找了很多库,发现拿不到视频文件的编码或者很麻烦,需要引入很大的依赖包
解决方案
最终的解决方案是判断视频能不能播放,有两种情况:
- 视频不能播放,会触发video的error事件
- 视频只有音频没有画面,不会触发error事件,但可以通过
video.videoWidth
属性判断
代码
<template>
<section>
<input type="file" @change="onUpload" />
<video
ref="video"
@error="onError"
@loadedmetadata="onLoad"
v-if="src"
:src="src"
controls
width="300"
></video>
</section>
</template>
<script>
export default {
name: 'test-video',
data() {
return {
src: '',
file: null,
}
},
methods: {
onUpload(e) {
const videoFile = e.target.files[0]
this.file = videoFile
this.src = URL.createObjectURL(videoFile)
},
onLoad() {
// 判断是否有画面
const hasFrame = this.$refs.video.videoWidth
if (!hasFrame) {
this.transcoding()
return
}
// ---处理视频逻辑
},
onError() {
console.log('on error')
this.transcoding()
},
transcoding() {
//上传并转码
},
},
}
</script>