本文基于开源项目decoder_wasm使用Angular开发的前端页面项目,对项目整理结构进行的改动,并使用Typescript重写大部分js源码,便于维护。 着重学习Angular框架下Worker,Wasm的使用,本人非前端开发从业人员,页面简陋请见谅。
从gitee上的开源项目decoder_wasm中可以获取到wasm文件。 https://gitee.com/wupeng-engineer/decoder_wasm/tree/master/dist
libffmpeg_264_265.js libffmpeg_264_265.wasm这两个文件emscripten编译生成的文件 拷贝到src/assets/wasm/目录下
├── assets │ └── wasm │ ├── libffmpeg_264_265.js │ └── libffmpeg_264_265.wasm在git仓库的Readme中有wasm的超简单的文档
wasm文件对外提供四个接口: openDecoder:初始化解码器; decodeData:解码传入的H.265码流数据; flushDecoder:清空缓存数据; closeDecoder:关闭解码器;创建组件
$ ng generate component WasmTest --skipTests=true CREATE src/app/wasm-test/wasm-test.component.scss (0 bytes) CREATE src/app/wasm-test/wasm-test.component.html (24 bytes) CREATE src/app/wasm-test/wasm-test.component.ts (287 bytes) UPDATE src/app/app.module.ts (686 bytes)设置路由
{ path: 'wasm', component: WasmTestComponent },修改angular.json文件,根据下图层级关系,在scripts数组中加上libffmpeg_264_265.js文件
{ "projects": { "AngularTest": { "architect": { "build": { "options": { "scripts": [ "src/assets/wasm/libffmpeg_264_265.js" ] } } } } } }修改tsconfig.json,根据下图层级关系,增加"allowJs":true,
{ "compilerOptions": { "allowJs":true } }注意:改配置文件需要重启angular服务;
由于angular的机制,libffmpeg_264_265.wasm文件会404, 需要修改一下libffmpeg_264_265.js中的wasm文件地址; 搜索"libffmpeg_264_265.wasm"改为正确的地址即可
var wasmBinaryFile = "assets/wasm/libffmpeg_264_265.wasm";修改wasm-test.component.ts文件
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-wasm-test', templateUrl: './wasm-test.component.html', styleUrls: ['./wasm-test.component.scss'] }) export class WasmTestComponent implements OnInit { private wasm = (window as any).Module as any; constructor() { console.log(`constructor ${typeof(this.wasm)}`); this.wasm = typeof this.wasm !== 'undefined' ? this.wasm : {}; this.wasm.onRuntimeInitialized = () => { console.log('onRuntimeInitialized'); const wasm = (window as any).Module as any; const decoderType = 0; const LOG_LEVEL_WASM = 1; const callback = wasm.addFunction(() => { }); wasm._openDecoder(decoderType, callback, LOG_LEVEL_WASM); }; console.log(`constructor ${typeof(this.wasm)}`); } ngOnInit(): void { } }打开 http://localhost:4200/wasm 控制台输出
Angular is running in the development mode. Call enableProdMode() to enable the production mode. client:52 [WDS] Live Reloading enabled. wasm-test.component.ts:14 onRuntimeInitialized libffmpeg_264_265.js:1138 [][Core][DT] Decoder initialized 0.可以看到网页已经可以调用wasm文件对外暴露的接口。
angular开发的单页面应用,wasm加载到window上会在整个应用上生效,通过angular配置加载wasm文件的方式只可以仅用于测试,后续会在worker中加载脚本。
下一篇介绍如何使用wasm文件
微信号:yjkhtddx