Needs and Problems

Preview the video uploaded locally by the user, and then do some actions (crop, add filters, etc.). However, Chrome can only preview videos encoded in H264. For videos that cannot be previewed by chrome, the front end needs to call the back end interface to upload and transcode the videos. The question is: How do you know if the browser can play the current video

The original idea

The first idea is to judge the encoding of the video file, if it is H264, it can be played, but found a lot of libraries, can not get the encoding of the video file or very troublesome, need to introduce a large dependency package

The solution

The final solution is to determine whether the video can be played, and there are two cases:

  1. The video cannot be played, and a video error event is triggered
  2. Video only has audio and no screen. It does not trigger an error event, but it can passvideo.videoWidthAttribute judgment

code

<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() {
            // Check whether there is a screen
            const hasFrame = this.$refs.video.videoWidth
            if(! hasFrame) {this.transcoding()
                return
            }
            // -- Processing video logic
        },
        onError() {
            console.log('on error')
            this.transcoding()
        },
        transcoding() {
            // Upload and transcode}},}</script>

Copy the code