ffmpeg.wasm实现网页操作视频

简介

ffmpeg.wasm是ffmpeg的纯Webassembly/Javascript端口。它可以在浏览器内录制视频和音频,并进行转换和流式传输。
在这里插入图片描述

源代码地址

github
加速地址

使用

vue2

  1. 新建vue2项目
  2. 安装@ffmpeg/ffmpeg @ffmpeg/core包
yarn add @ffmpeg/ffmpeg @ffmpeg/core

在这里插入图片描述
3. 编写代码

<template>
  <div id="app">
    <video :src="video" controls />
    <br>
    <input type="file" @change="tirggerFile($event)">
    <button @click="transcode">
      开始
    </button>
    <p>{{ message }}</p>
  </div>
</template>

<script>
import { createFFmpeg,fetchFile } from "@ffmpeg/ffmpeg";

export default {
  name: 'App',
  data() {
    return {
      message: "点击开始按钮开始执行",
      ffmpeg: null,
      video: "",
      file:null
    }
  },
  mounted() {
    this.ffmpeg = createFFmpeg({
      log: true,
    });
  },
  methods: {
    tirggerFile(event) {
      var files = event.target.files;
      console.log(files);
      this.file = files[0];
    },
    async transcode() {
      this.message = "加载 ffmeg-core.js";
      await this.ffmpeg.load();
      this.message = "开始转化";
      this.ffmpeg.FS("writeFile", "test.avi", await fetchFile(this.file));
      await this.ffmpeg.run("-i", "test.avi", "test.mp4");
      this.message = "完成";
      const data = this.ffmpeg.FS("readFile", "test.mp4");
      this.video = URL.createObjectURL(
        new Blob([data.buffer], { type: "video/mp4" })
      );
    }
  }
}
</script>
<style></style>
  1. 编辑vue.config.js
const path = require('path');
const express = require('express');
const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({
  transpileDependencies: true,
  publicPath:"/",
  configureWebpack: {
    devServer: {
      //如果vuecli是老版本需要使用before
      onBeforeSetupMiddleware: ({app}) => {
        app.use(
          "/node_modules/",
          express.static(path.resolve(__dirname, "node_modules"))
        );
        app.use((_, res, next) => {
          res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
          res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
          next();
        });
      }
    }
  }
})
  1. 运行测试项目

需要新版谷歌浏览器、edge浏览器以及火狐浏览器,360浏览器目前测试不可以。
在这里插入图片描述
选择视频文件然后点击开始
在这里插入图片描述

vue3

  1. 新建vue3项目
  2. 安装@ffmpeg/ffmpeg @ffmpeg/core包
    在这里插入图片描述
  3. 修改App.vue
<template>
  <video
    :src="video"
    controls
  />
  <br>
  <input type="file" @change="tirggerFile($event)">
  <button @click="transcode">
    Start
  </button>
  <p>{{ message }}</p>
</template>

<script>
import { createFFmpeg, fetchFile } from "@ffmpeg/ffmpeg";
import { defineComponent, ref } from "vue";

export default defineComponent({
  name: "App",

  setup() {
    // app state
    const ffmpeg = createFFmpeg({
      log: true,
    });
    const message = ref("Click Start to Transcode");
    let video = ref(null);
    let file ="/flame.avi"
      // process.env.NODE_ENV === "production"
      //   ? "/vue-app/flame.avi"
      //   : "/flame.avi";
    // methods
    async function transcode() {
      message.value = "Loading ffmeg-core.js";
      await ffmpeg.load();
      message.value = "Start transcoding";
      ffmpeg.FS("writeFile", "test.avi", await fetchFile(file));
      await ffmpeg.run("-i", "test.avi", "test.mp4");
      message.value = "Complete transcoding";
      const data = ffmpeg.FS("readFile", "test.mp4");
      video.value = URL.createObjectURL(
        new Blob([data.buffer], { type: "video/mp4" })
      );
    }

   function tirggerFile(event){
    var files = event.target.files;
    console.log(files);
    file = files[0];
  }
    return {
      video,
      message,
      transcode,
      tirggerFile
    };
  },

});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
  1. 修改vue.config.js
const zlib = require('zlib');
const path = require("path");
const express = require("express");
const { defineConfig } = require("@vue/cli-service");

module.exports = defineConfig({
  outputDir: "dist",
  indexPath: "index.html",
  transpileDependencies: false,
  productionSourceMap: true,
  runtimeCompiler: true,
  lintOnSave: true,
  parallel: true,
  integrity: true,
  publicPath: process.env.NODE_ENV === "production" ? "/vue-app/" : "/",
  configureWebpack: {
    devServer: {
      onBeforeSetupMiddleware: ({ app }) => {
        app.use(
          "/node_modules/",
          express.static(path.resolve(__dirname, "node_modules"))
        );
        app.use((_, res, next) => {
          res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
          res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
          next();
        });
      },
    },
  },
  pluginOptions: {
    compression: {
      brotli: {
        filename: '[file].br[query]',
        algorithm: 'brotliCompress',
        include: /\.(js|css|html|svg|json)(\?.*)?$/i,
        compressionOptions: {
          params: {
            [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
          },
        },
        minRatio: 0.8,
      },
      gzip: {
        filename: '[file].gz[query]',
        algorithm: 'gzip',
        include: /\.(js|css|html|svg|json)(\?.*)?$/i,
        compressionOptions: { level: zlib.constants.Z_BEST_COMPRESSION },
        minRatio: 0.8,
      },
    },
    prettify: false,
  },
});
  1. 运行测试项目
    同vue2

nginx部署

执行yarn run build打包,在nginx下新建文件夹ffmpegswam,将内容复制过去
在这里插入图片描述
修改nginx.conf文件
增加如下代码

 server {
        listen       8088;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            # set response header
            add_header 'Cross-Origin-Opener-Policy' 'same-origin';
            add_header 'Cross-Origin-Embedder-Policy' 'require-corp';
            root   ffmpegswam;
            index  index.html index.htm;
        }
    }

全部代码如下


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

 server {
        listen       8088;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            # set response header
            add_header 'Cross-Origin-Opener-Policy' 'same-origin';
            add_header 'Cross-Origin-Embedder-Policy' 'require-corp';
            root   ffmpegswam;
            index  index.html index.htm;
        }
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}
stream { 
    upstream mysql { 
    # 192.168.174.160 可修改为对应的 IP 地址和localhost 
    # 3306 可修改为对应的数据库端口 
    # weight 权重 
    server 192.168.189.129:3306 weight=1 max_fails=3 fail_timeout=30s; 
    }
    server {
         # 监听的端口 
         listen 3306; 
         proxy_connect_timeout 10s; 
         proxy_timeout 30s; 
         proxy_pass mysql; 
        }
}

启动nginx或者重新加载项目 nginx -s reload
访问lcoalhost:8088
在这里插入图片描述

如果是360浏览器运行报错如下
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假装我不帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值