1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
// deck-it - WAV for the assistant's voice questions
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// The daemon takes a WAV (desktop-assistant checks its header and length),
// and MediaRecorder gives webm/opus, so the clip is decoded, resampled to
// 16 kHz mono and written as 16-bit PCM here.
export function encodeWav(samples, rate) {
const buf = new ArrayBuffer(44 + samples.length * 2);
const v = new DataView(buf);
const tag = (o, s) => { for (let i = 0; i < 4; i++) v.setUint8(o + i, s.charCodeAt(i)); };
tag(0, "RIFF"); v.setUint32(4, 36 + samples.length * 2, true); tag(8, "WAVE");
tag(12, "fmt "); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true);
v.setUint16(34, 16, true);
tag(36, "data"); v.setUint32(40, samples.length * 2, true);
for (let i = 0; i < samples.length; i++) {
const s = Math.max(-1, Math.min(1, samples[i]));
v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);
}
return buf;
}
export async function toWav(blob, rate = 16000) {
const ctx = new AudioContext();
try {
const decoded = await ctx.decodeAudioData(await blob.arrayBuffer());
const off = new OfflineAudioContext(1, Math.ceil(decoded.duration * rate), rate);
const src = off.createBufferSource();
src.buffer = decoded;
src.connect(off.destination);
src.start();
return encodeWav((await off.startRendering()).getChannelData(0), rate);
} finally {
ctx.close();
}
}
|