简介
ffmpeg.wasm是ffmpeg的纯Webassembly/Javascript端口。它可以在浏览器内录制视频和音频,并进行转换和流式传输。
源代码地址
使用
vue2
- 新建vue2项目
- 安装@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>
- 编辑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();
});
}
}
}
})
- 运行测试项目
需要新版谷歌浏览器、edge浏览器以及火狐浏览器,360浏览器目前测试不可以。
选择视频文件然后点击开始
vue3
- 新建vue3项目
- 安装@ffmpeg/ffmpeg @ffmpeg/core包
- 修改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>
- 修改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,
},
});
- 运行测试项目
同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浏览器运行报错如下