Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(cook): WAV sources re-encode to MP3 - audio joins the compressed cook

esengine90a057bf4ca6
diff --git a/desktop/electron/audioCook.ts b/desktop/electron/audioCook.ts
new file mode 100644
index 000000000..f69cd77a5
--- /dev/null
+++ b/desktop/electron/audioCook.ts
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file audioCook.ts
+ * @brief Cook-time WAV → MP3 transcode. WAV parsing is plain RIFF walking
+ * (PCM 8/16/24/32-int and 32-float); encoding goes through the
+ * wasm-media-encoders LAME build (self-contained wasm, loaded lazily
+ * the first time a cook actually compresses audio). Already-compressed
+ * formats never come through here — the cook only routes `.wav`.
+ */
+
+interface ParsedWav {
+ channels: Float32Array[];
+ sampleRate: number;
+}
+
+/** Parse a RIFF/WAVE file into normalized float channels; null if not parseable. */
+export function parseWav(bytes: Uint8Array): ParsedWav | null {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (bytes.byteLength < 44) return null;
+ if (view.getUint32(0, false) !== 0x52494646 /* RIFF */) return null;
+ if (view.getUint32(8, false) !== 0x57415645 /* WAVE */) return null;
+
+ let formatTag = 0;
+ let channelCount = 0;
+ let sampleRate = 0;
+ let bitsPerSample = 0;
+ let dataOffset = -1;
+ let dataLength = 0;
+
+ let off = 12;
+ while (off + 8 <= bytes.byteLength) {
+ const id = view.getUint32(off, false);
+ const size = view.getUint32(off + 4, true);
+ const body = off + 8;
+ if (id === 0x666d7420 /* fmt */) {
+ formatTag = view.getUint16(body, true);
+ channelCount = view.getUint16(body + 2, true);
+ sampleRate = view.getUint32(body + 4, true);
+ bitsPerSample = view.getUint16(body + 14, true);
+ // WAVE_FORMAT_EXTENSIBLE: the real format sits in the SubFormat GUID.
+ if (formatTag === 0xfffe && size >= 40) {
+ formatTag = view.getUint16(body + 24, true);
+ }
+ } else if (id === 0x64617461 /* data */) {
+ dataOffset = body;
+ dataLength = Math.min(size, bytes.byteLength - body);
+ }
+ off = body + size + (size & 1); // chunks are word-aligned
+ }
+
+ if (dataOffset < 0 || channelCount < 1 || sampleRate <= 0) return null;
+ const isFloat = formatTag === 3;
+ const isPcm = formatTag === 1;
+ if (!isFloat && !isPcm) return null;
+ if (isFloat && bitsPerSample !== 32) return null;
+ if (isPcm && ![8, 16, 24, 32].includes(bitsPerSample)) return null;
+
+ const bytesPerSample = bitsPerSample / 8;
+ const frameSize = bytesPerSample * channelCount;
+ const frames = Math.floor(dataLength / frameSize);
+ // MP3 is mono/stereo; fold extra channels away by keeping the first two.
+ const outChannels = Math.min(2, channelCount);
+ const channels = Array.from({ length: outChannels }, () => new Float32Array(frames));
+
+ for (let f = 0; f < frames; f++) {
+ for (let c = 0; c < outChannels; c++) {
+ const p = dataOffset + f * frameSize + c * bytesPerSample;
+ let v: number;
+ if (isFloat) {
+ v = view.getFloat32(p, true);
+ } else if (bitsPerSample === 16) {
+ v = view.getInt16(p, true) / 0x8000;
+ } else if (bitsPerSample === 8) {
+ v = (view.getUint8(p) - 128) / 128;
+ } else if (bitsPerSample === 24) {
+ const u = view.getUint8(p) | (view.getUint8(p + 1) << 8) | (view.getUint8(p + 2) << 16);
+ v = (u >= 0x800000 ? u - 0x1000000 : u) / 0x800000;
+ } else {
+ v = view.getInt32(p, true) / 0x80000000;
+ }
+ channels[c][f] = Math.max(-1, Math.min(1, v));
+ }
+ }
+ return { channels, sampleRate };
+}
+
+type Mp3Encoder = {
+ configure(opts: { sampleRate: number; channels: 1 | 2; bitrate: number }): void;
+ encode(channels: Float32Array[]): Uint8Array;
+ finalize(): Uint8Array;
+};
+let encoderPromise: Promise<Mp3Encoder> | null = null;
+
+/** Transcode a WAV buffer to MP3 at `bitrateKbps`; null when the WAV doesn't parse. */
+export async function encodeWavToMp3(wav: Uint8Array, bitrateKbps: number): Promise<Uint8Array | null> {
+ const parsed = parseWav(wav);
+ if (!parsed) return null;
+ encoderPromise ??= import('wasm-media-encoders').then((m) => m.createMp3Encoder() as Promise<Mp3Encoder>);
+ const encoder = await encoderPromise;
+ encoder.configure({
+ sampleRate: parsed.sampleRate,
+ channels: parsed.channels.length as 1 | 2,
+ bitrate: bitrateKbps,
+ });
+ const head = encoder.encode(parsed.channels);
+ const tail = encoder.finalize();
+ const out = new Uint8Array(head.byteLength + tail.byteLength);
+ out.set(head, 0);
+ out.set(tail, head.byteLength);
+ return out;
+}
+
+/** Per-asset audio import settings from the `.meta` importer block (tolerant). */
+export function audioImportSettings(importer: Record<string, unknown> | undefined): {
+ compress: boolean; bitrateKbps: number;
+} {
+ const compress = importer?.compress;
+ const bitrate = importer?.bitrateKbps;
+ return {
+ compress: typeof compress === 'boolean' ? compress : true,
+ bitrateKbps: bitrate === 96 || bitrate === 128 || bitrate === 192 ? (bitrate as number) : 128,
+ };
+}
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index 6914eeb43..f59b2fa26 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -197,11 +197,13 @@ export async function cookAssets(
opts: {
entryScenes: string[]; outDir: string;
contentAddressed?: boolean; compressTextures?: boolean; atlasTextures?: boolean;
+ compressAudio?: boolean;
},
): Promise<CookResult> {
const contentAddressed = opts.contentAddressed ?? false;
const compressTextures = opts.compressTextures ?? false;
const atlasTextures = opts.atlasTextures ?? false;
+ const compressAudio = opts.compressAudio ?? false;
const { index } = await scanAssetDatabase(root, { write: false });
const byUuid = new Map(index.entries.map((e) => [e.uuid, e]));
const byPath = new Map(index.entries.map((e) => [e.path, e]));
@@ -259,6 +261,12 @@ export async function cookAssets(
const enc = await import('../../build-tools/basis/encoder.mjs');
encodePng = (png) => enc.encodePngToKtx2(png, { mode: 'uastc' });
}
+ // WAV → MP3 (LAME wasm) rides the same lazy pattern; per-asset importer
+ // settings can opt a clip out (seamless loops) or pick a bitrate.
+ let audioEnc: typeof import('./audioCook') | null = null;
+ if (compressAudio) {
+ audioEnc = await import('./audioCook');
+ }
const manifestEntries: CookManifestEntry[] = [];
const staged = new Set<string>(); // staged output paths, for content-addressed dedup
@@ -369,6 +377,20 @@ export async function cookAssets(
ext = '.ktx2';
compressedFormats = COMPRESSED_TARGETS;
}
+ // WAV sources re-encode to MP3 (universal decode); other audio formats are
+ // already compressed and pass through. Hash + name reflect the ENCODED bytes.
+ if (audioEnc && ext.toLowerCase() === '.wav') {
+ const settings = audioEnc.audioImportSettings(entry.importer);
+ if (settings.compress) {
+ const mp3 = await audioEnc.encodeWavToMp3(data, settings.bitrateKbps);
+ if (mp3 && mp3.byteLength < data.byteLength) {
+ data = mp3;
+ ext = '.mp3';
+ } else if (!mp3) {
+ warnings.push(`${entry.path}: WAV parse failed — shipped raw`);
+ }
+ }
+ }
// Materials: relative refs → logical project paths (see rewriteMaterialRefs).
if (ext.toLowerCase() === '.esmaterial') {
try {
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index 3d03b3a60..54ddf2b4a 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -265,6 +265,7 @@ export async function exportGame(opts: {
/** Encode raster textures to GPU-compressed KTX2 at cook time. Default off
* (lossy + encode-time cost — opt in per project). */
compressTextures?: boolean;
+ compressAudio?: boolean;
/** Pack `<name>.atlas/` folder PNGs into atlas pages at cook time. Default off. */
atlasTextures?: boolean;
title?: string;
@@ -308,6 +309,7 @@ export async function exportGame(opts: {
minify: opts.minify,
contentAddressed: opts.contentAddressed,
compressTextures: opts.compressTextures,
+ compressAudio: opts.compressAudio,
atlasTextures: opts.atlasTextures,
onProgress: opts.onProgress,
});
@@ -352,7 +354,7 @@ export async function exportGame(opts: {
// 1. Cook reachable assets + manifest, from EVERY shippable scene as a root
// (the scene files themselves are staged too).
progress({ phase: 'Cooking assets' });
- const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });
+ const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures });
warnings.push(...cook.warnings);
progress({ phase: 'Cooking assets', detail: `${cook.included.length} reachable` });
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
index 1223a5aa1..396491d9b 100644
--- a/desktop/electron/exportWeChat.ts
+++ b/desktop/electron/exportWeChat.ts
@@ -261,6 +261,7 @@ export async function exportWeChat(opts: {
contentAddressed?: boolean;
/** Encode raster textures to GPU-compressed KTX2 at cook time. */
compressTextures?: boolean;
+ compressAudio?: boolean;
/** Pack `<name>.atlas/` folder PNGs into atlas pages at cook time. */
atlasTextures?: boolean;
onProgress?: OnExportProgress;
@@ -299,7 +300,7 @@ export async function exportWeChat(opts: {
// manifest. KTX2 textures are fine here: the scan below sees the staged
// .ktx2 files and ships the Basis transcoder side module with them.
progress({ phase: 'Cooking assets' });
- const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });
+ const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures });
warnings.push(...cook.warnings);
// 1a. Restage for WeChat's code-package suffix whitelist (it has no `ktx2`
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 806a80983..97fb2db93 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -565,7 +565,7 @@ ipcMain.handle('project:cookAssets', async (_e, outDir?: string) => {
// Export a runnable web build (play == ship): cook + game host + wasm + index.html.
ipcMain.handle(
'project:exportGame',
- async (e, opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; atlasTextures?: boolean }) => {
+ async (e, opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }) => {
const root = requireRoot();
const manifest = await readManifest(root);
const entryScene = manifest.defaultScene;
@@ -600,6 +600,7 @@ ipcMain.handle(
minify: opts?.minify,
sourcemap: opts?.sourcemap,
compressTextures: opts?.compressTextures,
+ compressAudio: opts?.compressAudio,
atlasTextures: opts?.atlasTextures,
onProgress: (p) => e.sender.send('project:exportProgress', p),
});
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 3dbe9d19c..01799eb40 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -87,7 +87,7 @@ const api = {
/** Cook reachable assets for shipping → staged files + runtime manifest in `outDir`. */
cookAssets: (outDir?: string): Promise<CookResult> => ipcRenderer.invoke('project:cookAssets', outDir),
/** Export a runnable web build (play==ship) → self-contained `outDir` (default dist-game/). */
- exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; atlasTextures?: boolean }): Promise<ExportGameResult> =>
+ exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }): Promise<ExportGameResult> =>
ipcRenderer.invoke('project:exportGame', opts),
/** Serve a built export dir (web / playable) over loopback http and open it in the
* default browser — the build's real deployment surface, so no file:// origin
diff --git a/desktop/package.json b/desktop/package.json
index 63e6bd36a..b074222be 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -71,6 +71,7 @@
"pngjs": "^7.0.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
+ "wasm-media-encoders": "^0.7.0",
"zustand": "^5.0.14"
},
"devDependencies": {
diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsx
index 47638a040..1aabe674f 100644
--- a/desktop/src/components/BuildDialog.tsx
+++ b/desktop/src/components/BuildDialog.tsx
@@ -99,6 +99,7 @@ export function BuildDialog() {
const [sourceMaps, setSourceMaps] = useState(saved.sourceMaps ?? false);
const [compressTextures, setCompressTextures] = useState(saved.compressTextures ?? false);
const [atlasTextures, setAtlasTextures] = useState(saved.atlasTextures ?? false);
+ const [compressAudio, setCompressAudio] = useState(saved.compressAudio ?? false);
const [phase, setPhase] = useState<Phase>('idle');
const [result, setResult] = useState<Result | null>(null);
const [log, setLog] = useState<string[]>([]);
@@ -135,7 +136,7 @@ export function BuildDialog() {
setResult(null);
setLog([]);
// Persist the chosen settings to project.esproject (restored next time).
- void ProjectStore.setPackaging({ platform, config, sourceMaps, openFolder, compressTextures, atlasTextures, outDir: { [platform]: outDir } });
+ void ProjectStore.setPackaging({ platform, config, sourceMaps, openFolder, compressTextures, atlasTextures, compressAudio, outDir: { [platform]: outDir } });
// Live build log (UE-style): each export phase streams over IPC.
const unsub = window.estella.project?.onExportProgress?.((p) =>
setLog((l) => [...l, p.detail ? `${p.phase} — ${p.detail}` : p.phase]),
@@ -148,6 +149,7 @@ export function BuildDialog() {
sourcemap: def.sourceMaps && sourceMaps,
compressTextures,
atlasTextures,
+ compressAudio,
})) as Result | null;
if (!res) {
setResult({ ok: false, outDir, included: 0, warnings: [], errors: [t('build.noProjectOpen')] });
@@ -269,6 +271,10 @@ export function BuildDialog() {
<input type="checkbox" checked={atlasTextures} onChange={(e) => setAtlasTextures(e.target.checked)} />
{t('build.atlasTextures')}
</label>
+ <label className="bd-check" title={t('build.compressAudioTip')}>
+ <input type="checkbox" checked={compressAudio} onChange={(e) => setCompressAudio(e.target.checked)} />
+ {t('build.compressAudio')}
+ </label>
{def.prereq && (
<div className="build__prereq">
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index db18c1940..b53436123 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -62,6 +62,11 @@ export const projectMessages = defineMessages({
'build.openFolderWhenDone': { en: 'Open output folder when done', zh: '完成后打开输出文件夹' },
'build.includeSourceMaps': { en: 'Include source maps', zh: '包含源码映射' },
'build.compressTextures': { en: 'Compress textures (PNG → KTX2)', zh: '压缩纹理(PNG → KTX2)' },
+ 'build.compressAudio': { en: 'Compress audio (WAV → MP3)', zh: '压缩音频(WAV → MP3)' },
+ 'build.compressAudioTip': {
+ en: 'Re-encode WAV sources to MP3 at cook. Per-asset Import Settings can opt a clip out (seamless loops) or pick a bitrate.',
+ zh: '打包时将 WAV 源重编码为 MP3。可在资产的导入设置中单独关闭(无缝循环素材)或选择码率。',
+ },
'build.atlasTextures': { en: 'Pack .atlas folders into atlases', zh: '将 .atlas 文件夹打包为图集' },
// — Scenes in build —
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 8bc6df04f..119420387 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1299,7 +1299,7 @@ class ProjectStoreImpl {
* (default `dist-game/`). Returns the bridge result so the Build dialog can
* render status/log; null if no project is open.
*/
- async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; atlasTextures?: boolean }) {
+ async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }) {
if (!this.state) return null;
return window.estella.project.exportGame(opts);
}
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index 47d4f5620..714f8af1c 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -109,6 +109,8 @@ export interface ProjectPackaging {
openFolder?: boolean;
/** Cook PNGs to GPU-ready KTX2 (Basis Universal). */
compressTextures?: boolean;
+ /** Cook WAV sources to MP3 (per-asset Import Settings can override). */
+ compressAudio?: boolean;
/** Pack `<name>.atlas/` folders into atlas pages at cook time. */
atlasTextures?: boolean;
/** Project-relative scene paths NOT shipped as switchable scenes (dev/test
diff --git a/desktop/tests/audio-cook.test.ts b/desktop/tests/audio-cook.test.ts
new file mode 100644
index 000000000..5c8b684e5
--- /dev/null
+++ b/desktop/tests/audio-cook.test.ts
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Cook-time audio: WAV parsing (PCM16/24/float, extensible, word-aligned
+ * chunks) and the WAV→MP3 transcode through the real LAME wasm encoder.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseWav, encodeWavToMp3, audioImportSettings } from '../electron/audioCook';
+
+/** Build a minimal RIFF/WAVE file. */
+function makeWav(opts: {
+ formatTag?: number; channels?: number; sampleRate?: number; bits?: number;
+ frames?: number; sample?: (frame: number, ch: number) => number;
+}): Uint8Array {
+ const formatTag = opts.formatTag ?? 1;
+ const channels = opts.channels ?? 1;
+ const rate = opts.sampleRate ?? 44100;
+ const bits = opts.bits ?? 16;
+ const frames = opts.frames ?? 100;
+ const sample = opts.sample ?? ((f) => Math.sin(f / 10) * 0.5);
+ const bytesPer = bits / 8;
+ const dataSize = frames * channels * bytesPer;
+ const buf = new ArrayBuffer(44 + dataSize);
+ const v = new DataView(buf);
+ const w4 = (o: number, s: string) => { for (let i = 0; i < 4; i++) v.setUint8(o + i, s.charCodeAt(i)); };
+ w4(0, 'RIFF'); v.setUint32(4, 36 + dataSize, true); w4(8, 'WAVE');
+ w4(12, 'fmt '); v.setUint32(16, 16, true);
+ v.setUint16(20, formatTag, true); v.setUint16(22, channels, true);
+ v.setUint32(24, rate, true); v.setUint32(28, rate * channels * bytesPer, true);
+ v.setUint16(32, channels * bytesPer, true); v.setUint16(34, bits, true);
+ w4(36, 'data'); v.setUint32(40, dataSize, true);
+ for (let f = 0; f < frames; f++) {
+ for (let c = 0; c < channels; c++) {
+ const off = 44 + (f * channels + c) * bytesPer;
+ const s = sample(f, c);
+ if (formatTag === 3) v.setFloat32(off, s, true);
+ else if (bits === 16) v.setInt16(off, Math.round(s * 0x7fff), true);
+ else if (bits === 24) {
+ const u = (Math.round(s * 0x7fffff) + 0x1000000) & 0xffffff;
+ v.setUint8(off, u & 0xff); v.setUint8(off + 1, (u >> 8) & 0xff); v.setUint8(off + 2, (u >> 16) & 0xff);
+ }
+ }
+ }
+ return new Uint8Array(buf);
+}
+
+describe('parseWav', () => {
+ it('parses PCM16 stereo', () => {
+ const wav = makeWav({ channels: 2, frames: 50, sample: (f, c) => (c === 0 ? 0.5 : -0.5) });
+ const parsed = parseWav(wav)!;
+ expect(parsed.sampleRate).toBe(44100);
+ expect(parsed.channels).toHaveLength(2);
+ expect(parsed.channels[0][10]).toBeCloseTo(0.5, 2);
+ expect(parsed.channels[1][10]).toBeCloseTo(-0.5, 2);
+ });
+
+ it('parses 32-bit float and 24-bit PCM', () => {
+ const f32 = parseWav(makeWav({ formatTag: 3, bits: 32, sample: () => 0.25 }))!;
+ expect(f32.channels[0][5]).toBeCloseTo(0.25, 5);
+ const p24 = parseWav(makeWav({ bits: 24, sample: () => 0.25 }))!;
+ expect(p24.channels[0][5]).toBeCloseTo(0.25, 3);
+ });
+
+ it('rejects non-WAV bytes', () => {
+ expect(parseWav(new Uint8Array(100))).toBeNull();
+ expect(parseWav(new TextEncoder().encode('OggS' + 'x'.repeat(60)))).toBeNull();
+ });
+});
+
+describe('encodeWavToMp3', () => {
+ it('re-encodes a WAV to a smaller MP3', async () => {
+ const wav = makeWav({ frames: 44100, sample: (f) => Math.sin((f / 44100) * 2 * Math.PI * 440) * 0.7 });
+ const mp3 = await encodeWavToMp3(wav, 128);
+ expect(mp3).not.toBeNull();
+ // MP3 frame sync at the start (0xFFEx) or an ID3/LAME header.
+ expect(mp3!.byteLength).toBeGreaterThan(1000);
+ expect(mp3!.byteLength).toBeLessThan(wav.byteLength);
+ }, 30000);
+
+ it('returns null for unparseable input', async () => {
+ expect(await encodeWavToMp3(new Uint8Array(64), 128)).toBeNull();
+ });
+});
+
+describe('audioImportSettings', () => {
+ it('defaults and validates', () => {
+ expect(audioImportSettings(undefined)).toEqual({ compress: true, bitrateKbps: 128 });
+ expect(audioImportSettings({ compress: false, bitrateKbps: 192 })).toEqual({ compress: false, bitrateKbps: 192 });
+ expect(audioImportSettings({ bitrateKbps: 999 })).toEqual({ compress: true, bitrateKbps: 128 });
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 67e4e7783..538a5d1f9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -47,6 +47,9 @@ importers:
react-dom:
specifier: ^19.2.0
version: 19.2.7([email protected])
+ wasm-media-encoders:
+ specifier: ^0.7.0
+ version: 0.7.0
zustand:
specifier: ^5.0.14
version: 5.0.14(@types/[email protected])([email protected])
@@ -917,6 +920,9 @@ packages:
resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}
+
'@szmarczak/[email protected]':
resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}
engines: {node: '>=10'}
@@ -2881,6 +2887,10 @@ packages:
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-Sp4wUasgxOK/IFfNhpon6LQQgYGwtpxyV4isjGIe1rvhnJL3w2KYr4f+CdqDNtGPDcgCDRY+uBanVfSx6Si0WQ==}
+ engines: {node: '>= 10'}
+
resolution: {integrity: sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==}
@@ -3598,6 +3608,10 @@ snapshots:
'@sindresorhus/[email protected]': {}
+ dependencies:
+ tslib: 2.8.1
+
'@szmarczak/[email protected]':
dependencies:
defer-to-connect: 2.0.1
@@ -5725,6 +5739,10 @@ snapshots:
xml-name-validator: 5.0.0
optional: true
+ dependencies:
+ '@swc/helpers': 0.5.23
+
dependencies:
'@peculiar/asn1-schema': 2.8.0