基于webassembly的H265视频播放器前端Angular学习笔记2:创建Angular组件获取H265文件数据
本文基于开源项目decoder_wasm使用Angular开发的前端页面项目,对项目整理结构进行的改动,并使用Typescript重写大部分js源码,便于维护。
着重学习Angular框架下Worker,Wasm的使用,本人非前端开发从业人员,页面简陋请见谅。
创建简单的界面读取H265文件内容
简单的界面
创建组件
$ ng generate component CanvasTest --skipTests=true
CREATE src/app/canvas-test/canvas-test.component.scss (0 bytes)
CREATE src/app/canvas-test/canvas-test.component.html (26 bytes)
CREATE src/app/canvas-test/canvas-test.component.ts (295 bytes)
UPDATE src/app/app.module.ts (594 bytes)
设置路由
{ path: 'canvas', component: CanvasTestComponent },
修改canvas-test.component.html
<div style="margin: 20px; display: inline;">
H265文件:
<input type="file" #H265FileInput (change)="play(H265FileInput.files);">
</div>
<div style="margin-top: 10px; display: block; width: 540px; height: 360px; background-color: black;">
<canvas id="playCanvas"></canvas>
</div>
选中文件后直接执行play方法读取文件内容
读取H265文件内容
play函数读取H265文件内容,canvas-test.component.ts
import { Component, OnInit } from '@angular/core';
const CHUNK_SIZE = 4096;
@Component({
selector: 'app-canvas-test',
templateUrl: './canvas-test.component.html',
styleUrls: ['./canvas-test.component.scss']
})
export class CanvasTestComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
play(files: Array<File>) {
console.log(files);
const file = files[0];
let filePos = 0;
let streamSize = 0;
do {
const reader = new FileReader();
reader.onload = (ev: ProgressEvent<FileReader>) => {
const typedArray: ArrayBuffer = ev.target.result as ArrayBuffer;
const size = typedArray.byteLength;
console.log(size);
console.count(`onload`);
console.log(ev);
};
streamSize = this.readFileSlice(reader, file, filePos, CHUNK_SIZE);
filePos += streamSize;
} while (streamSize > 0);
}
private readFileSlice(reader: FileReader, file: File, startAddr: number, size: number) {
const fileSize = file.size;
let fileSlice: Blob;
if (startAddr > fileSize - 1) {
return 0;
}
else if (startAddr + size > fileSize - 1) {
// fileSlice = this.blob_slice(file, startAddr, fileSize);
fileSlice = file.slice(startAddr, fileSize);
reader.readAsArrayBuffer(fileSlice);
return fileSize - startAddr;
}
else {
fileSlice = file.slice(startAddr, startAddr + size);
// fileSlice = this.blob_slice(file, startAddr, startAddr + size);
reader.readAsArrayBuffer(fileSlice);
return size;
}
}
}
下一篇介绍如何加载wasm文件.
微信号:yjkhtddx