概述WebCodecs 提供高性能的编解码接口。本文展示解码帧并生成缩略图存储的流程。能力检测与解码const supportsWC = typeof VideoDecoder === 'function'; async function decodeFrames(blob, onFrame) { if (!supportsWC) throw new Error('unsupported'); const ab = await blob.arrayBuffer(); const decoder = new VideoDecoder({ output: onFrame, error: e => console.error(e) }); decoder.configure({ codec: 'vp8' }); const chunk = new EncodedVideoChunk({ type: 'key', timestamp: 0, data: new Uint8Array(ab) }); decoder.decode(chunk); } 帧转缩略图与持久化function openDB(name) { return new Promise((resolve, reject) => { const r = indexedDB.open(name, 1); r.onupgradeneeded = () => { const db = r.result; if (!db.objectStoreNames.contains('thumbs')) db.createObjectStore('thumbs', { keyPath:'id' }); }; r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); } async function saveThumb(id, blob) { const db = await openDB('videodb'); const tx = db.transaction('thumbs','readwrite'); tx.objectStore('thumbs').put({ id, blob }); await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); }); db.close(); } async function frameToThumb(frame, id) { const canvas = document.createElement('canvas'); canvas.width = frame.codedWidth; canvas.height = frame.codedHeight; const ctx = canvas.getContext('2d'); const bmp = await createImageBitmap(frame); ctx.drawImage(bmp, 0, 0); const blob = await new Promise(r => canvas.toBlob(r, 'image/jpeg', 0.8)); await saveThumb(id, blob); }

发表评论 取消回复