dither4/pack-wav.js

87 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2022-11-30 07:59:38 +00:00
import wavefile from 'wavefile';
let WaveFile = wavefile.WaveFile;
import {
readFileSync,
writeFileSync
} from 'fs';
function byte2byte(arr) {
let lines = [];
for (let i=0; i < arr.length; i++) {
lines.push(`.byte ${arr[i]}`);
}
return lines.join('\n');
}
2024-08-31 17:58:15 +00:00
class Dither {
constructor() {
this.err = 0;
}
to4bit(val8) {
let val = (val8 / 255) - this.err;
if (val < 0) {
val = 0;
}
if (val > 1) {
val = 1;
}
let val4 = Math.round(val * 15);
let dithered = (val4 / 15);
this.err = (dithered - val);
return val4;
2022-11-30 07:59:38 +00:00
}
}
function pack(audio) {
let packed = [];
2024-08-31 17:58:15 +00:00
let dither = new Dither();
2022-11-30 07:59:38 +00:00
for (let i = 0; i < audio.length; i += 2) {
2022-12-08 00:12:15 +00:00
// little-endian 4-bit samples
2024-08-31 17:58:15 +00:00
let low = dither.to4bit(audio[i]);
let high = dither.to4bit(audio[i + 1]);
2022-11-30 07:59:38 +00:00
let byte = low | (high << 4);
packed.push(byte);
}
2024-08-31 17:58:15 +00:00
/*
2022-12-08 00:12:15 +00:00
// raw push bytes
2022-11-30 12:01:55 +00:00
for (let i = 0; i < audio.length; i += 2) {
let val = to4bit(audio[i]);
let byte = val | 0x10;
packed.push(byte);
}
2024-08-31 17:58:15 +00:00
*/
2022-11-30 07:59:38 +00:00
return packed;
}
function audio2assembly(audio) {
2022-12-11 21:09:14 +00:00
return `
.segment "AUDIO"
2022-11-30 07:59:38 +00:00
.export audio_samples
.export audio_samples_end
audio_samples:
${byte2byte(pack(audio))}
audio_samples_end:
2022-12-08 19:47:04 +00:00
.byte 24
2022-11-30 07:59:38 +00:00
`;
}
function wav2assembly(buffer) {
let wav = new WaveFile(buffer);
let samples = wav.getSamples();
let n = samples.length - (samples.length % 131);
2022-12-08 19:47:04 +00:00
return audio2assembly(samples.slice(0, n));
2022-11-30 07:59:38 +00:00
}
let infile = process.argv[2];
let outfile = process.argv[3];
let buffer = readFileSync(infile);
let asm = wav2assembly(buffer);
writeFileSync(outfile, asm, 'utf-8');