DEV Community

Cover image for How to export WAV files and ZIP archives entirely in the browser with vanilla JavaScript
SecondWindMC
SecondWindMC

Posted on Edited on

How to export WAV files and ZIP archives entirely in the browser with vanilla JavaScript

I recently needed a small browser tool that could generate retro game sound effects and export several variations at once.

The constraints were:

  • no account or backend
  • no audio upload
  • no external ZIP library
  • plain HTML/JavaScript that can be hosted on GitHub Pages
  • output useful enough for a real game project

The result is Retro SFX Lab, a free local browser SFX generator. Its newest version can batch-export five WAV variations as a ZIP, including a usage/license README and a settings.json file for reproducing the sounds.

The complete source is CC0 here:

https://github.com/SecondWindMC/CircuitUI-SFX/blob/main/tools/retro-sfx-lab.html

Here is how the two important pieces work.

1. Writing a WAV file locally

A basic PCM WAV file is binary data with a 44-byte header followed by 16-bit samples. Once the generated audio exists as a Float32Array, the export is mostly careful byte packing:

function wavBlob(data) {
  const samples = data.samples;
  const sampleRate = data.sr;
  const buffer = new ArrayBuffer(44 + samples.length * 2);
  const view = new DataView(buffer);

  const writeString = (offset, text) => {
    for (let i = 0; i < text.length; i++) {
      view.setUint8(offset + i, text.charCodeAt(i));
    }
  };

  writeString(0, 'RIFF');
  view.setUint32(4, 36 + samples.length * 2, true);
  writeString(8, 'WAVEfmt ');
  view.setUint32(16, 16, true);       // PCM chunk size
  view.setUint16(20, 1, true);        // PCM format
  view.setUint16(22, 1, true);        // mono
  view.setUint32(24, sampleRate, true);
  view.setUint32(28, sampleRate * 2, true);
  view.setUint16(32, 2, true);        // block alignment
  view.setUint16(34, 16, true);       // bits per sample
  writeString(36, 'data');
  view.setUint32(40, samples.length * 2, true);

  for (let i = 0; i < samples.length; i++) {
    const x = Math.max(-1, Math.min(1, samples[i]));
    view.setInt16(44 + i * 2, x < 0 ? x * 32768 : x * 32767, true);
  }

  return new Blob([buffer], { type: 'audio/wav' });
}
Enter fullscreen mode Exit fullscreen mode

The important details are little-endian byte order, correct RIFF chunk sizes, and clamping floating-point samples before converting them to signed 16-bit PCM.

For a single file, downloading it is just an object URL:

const a = document.createElement('a');
a.href = URL.createObjectURL(wavBlob(data));
a.download = 'retro-sfx.wav';
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 2000);
Enter fullscreen mode Exit fullscreen mode

2. ZIP files are simpler than they look

A ZIP archive does not have to compress its entries. The simplest valid ZIP uses the STORE method: files are concatenated uncompressed, each with a small header, followed by a central directory.

The one nontrivial requirement is CRC32. A small table-based implementation is enough:

function crc32(data) {
  crc32.table = crc32.table || (() => {
    const table = new Uint32Array(256);
    for (let n = 0; n < 256; n++) {
      let c = n;
      for (let k = 0; k < 8; k++) {
        c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
      }
      table[n] = c >>> 0;
    }
    return table;
  })();

  let c = ~0;
  for (let i = 0; i < data.length; i++) {
    c = crc32.table[(c ^ data[i]) & 255] ^ (c >>> 8);
  }
  return (~c) >>> 0;
}
Enter fullscreen mode Exit fullscreen mode

Then each file becomes:

  1. a local file header
  2. the file name bytes
  3. the uncompressed file bytes
  4. a central-directory entry pointing to that local header

For small generated WAV files, skipping compression is fine. It makes the implementation small, predictable, and easy to audit. The resulting archive opens correctly in normal ZIP tools because the format still records correct CRCs, sizes, names, offsets, and directory entries.

3. Batch-exporting reproducible variations

For the SFX tool, each variation is generated by jittering the current sound parameters slightly:

function variedParams(base) {
  const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
  const jitter = (v, amount, min, max) =>
    clamp(v * (1 + (Math.random() * 2 - 1) * amount), min, max);

  return {
    ...base,
    start: Math.round(jitter(base.start, 0.18, 40, 1800)),
    end: Math.round(jitter(base.end, 0.18, 30, 1800)),
    dur: Number(jitter(base.dur, 0.15, 0.03, 1.2).toFixed(2)),
    noise: clamp(base.noise + (Math.random() * 2 - 1) * 0.14, 0, 1)
  };
}
Enter fullscreen mode Exit fullscreen mode

The export loop keeps the parameters alongside the generated audio:

const files = [];
const settings = [];

for (let i = 1; i <= 5; i++) {
  const params = variedParams(base);
  const audio = synth(params);
  const wavBytes = new Uint8Array(await wavBlob(audio).arrayBuffer());
  const name = `variation-${String(i).padStart(2, '0')}.wav`;

  settings.push({ file: name, parameters: params });
  files.push({ name, data: wavBytes });
}
Enter fullscreen mode Exit fullscreen mode

Then the archive gets two extra text entries:

const encoder = new TextEncoder();

files.push({
  name: 'README.txt',
  data: encoder.encode(
    'Generated locally with Retro SFX Lab. ' +
    'Generated sounds may be used commercially; attribution is appreciated but not required.'
  )
});

files.push({
  name: 'settings.json',
  data: encoder.encode(JSON.stringify({ variations: settings }, null, 2))
});
Enter fullscreen mode Exit fullscreen mode

That last step matters more than it first appears. A ZIP full of anonymous WAVs is useful for a jam, but a ZIP that also explains usage rights and preserves the exact synthesis parameters is much easier to drop into a real project.

Why avoid dependencies here?

For a large application, using a mature ZIP library is usually the right decision. This case is different: the files are small, compression is unnecessary, the archive structure is fixed, and the whole tool is intentionally a single static HTML page. Implementing the tiny subset of ZIP needed for STORE entries keeps the page self-contained and avoids a supply-chain dependency for a simple export feature.

The full implementation is public domain/CC0, so you can inspect or reuse it:

The newest version also includes attack-time and decay-shape controls, and those parameters are included in shareable URLs and batch-export settings.json. If you try it, I would be interested in which export controls would make it more useful for real game jams: more variation count options, additional envelope controls, or engine-specific naming conventions.

Top comments (1)

Collapse
 
kamalmosadegh profile image
Kamal Mosadegh •

This is exactly the kind of no-dependency export I wish more browser games shipped with. The settings.json step is the part I would underline — five jittered WAVs are only useful if you can reproduce the one you liked, and most export tools lose that. Two checks I would add, from building VOIDSTORM as an HTML5 game: first, verify the WAV by decoding it back and comparing the sample count against the Float32Array you packed — a wrong RIFF chunk size will still play in some players and fail silently in others. Second, log the peak amplitude per variation in settings.json as well; a jittered variation that clips at 1.0 sounds very different from one that peaks at 0.8, and that number is what tells you which variation to keep. STORE is the right call at this size — five 16-bit WAVs are small enough that compression saves little, and the CRC32 table is the only real complexity. One question: do the attack-time and decay-shape controls also get jittered across the five variations, or are they fixed while the other parameters vary?