diff --git a/web/src/App.tsx b/web/src/App.tsx index b010a4d..eb3c41f 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -18,6 +18,7 @@ import { AudioPlayer, MicCapture, SAMPLE_RATE, + encodeWavStereo, hasNativeOutputPicker, listAudioInputDevices, listAudioOutputDevices, @@ -2068,9 +2069,9 @@ function AppInner() { const audioContextRef = useRef(null); const audioPlayerRef = useRef(null); const micCaptureRef = useRef(null); - const recorderRef = useRef(null); - const recordDestRef = useRef(null); - const recordedChunksRef = useRef([]); + const recordProcessorRef = useRef(null); + const recordSilenceRef = useRef(null); + const recordChunksRef = useRef<{ left: Float32Array[]; right: Float32Array[] }>({ left: [], right: [] }); const activeTabRef = useRef("channel"); const hasConnectedRef = useRef(false); // Set when a "disconnected" event is received, so the socket's onclose @@ -2833,51 +2834,75 @@ function AppInner() { // Connects the current mic (if any) into the active recording, so a device // switch or a mic (re)start mid-recording doesn't silently drop it from the mix. const connectMicToRecorder = () => { - const dest = recordDestRef.current; + const processor = recordProcessorRef.current; const source = micCaptureRef.current?.getSourceNode(); - if (dest && source) source.connect(dest); + if (processor && source) source.connect(processor); }; const startRecording = () => { - if (recorderRef.current) return; + if (recordProcessorRef.current) return; const audioContext = ensureAudioContext(); - const dest = audioContext.createMediaStreamDestination(); - recordDestRef.current = dest; - audioPlayerRef.current?.getInputNode().connect(dest); + // Captures raw PCM via a ScriptProcessorNode (rather than MediaRecorder) so the + // download can be an uncompressed WAV instead of a browser-codec-dependent webm/ogg. + const processor = audioContext.createScriptProcessor(4096, 2, 2); + const silence = audioContext.createGain(); + silence.gain.value = 0; + recordChunksRef.current = { left: [], right: [] }; + processor.onaudioprocess = (event) => { + const left = event.inputBuffer.getChannelData(0); + const right = event.inputBuffer.numberOfChannels > 1 ? event.inputBuffer.getChannelData(1) : left; + recordChunksRef.current.left.push(left.slice()); + recordChunksRef.current.right.push(right.slice()); + }; + // A ScriptProcessorNode only fires while connected to a destination; route + // through a muted gain node so the recording tap isn't also heard. + processor.connect(silence); + silence.connect(audioContext.destination); + recordProcessorRef.current = processor; + recordSilenceRef.current = silence; + audioPlayerRef.current?.getInputNode().connect(processor); connectMicToRecorder(); - recordedChunksRef.current = []; - const recorder = new MediaRecorder(dest.stream); - recorder.ondataavailable = (event) => { - if (event.data.size > 0) recordedChunksRef.current.push(event.data); - }; - recorder.onstop = () => { - const blob = new Blob(recordedChunksRef.current, { type: recorder.mimeType || "audio/webm" }); - recordedChunksRef.current = []; - const extension = blob.type.includes("ogg") ? "ogg" : "webm"; - const safeServerName = (serverName || "session").replace(/[\\/:*?"<>|]+/g, "_").trim() || "session"; - const filename = `webspeak3-${safeServerName}-${new Date().toISOString().replace(/[:.]/g, "-")}.${extension}`; - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - a.remove(); - URL.revokeObjectURL(url); - logClient("info", "Recording", `Saved recording as ${filename}`); - }; - recorder.start(); - recorderRef.current = recorder; setRecording(true); logClient("info", "Recording", "Started local recording"); }; const stopRecording = () => { - recorderRef.current?.stop(); - recorderRef.current = null; - recordDestRef.current = null; + const processor = recordProcessorRef.current; + if (!processor) return; + processor.onaudioprocess = null; + processor.disconnect(); + recordSilenceRef.current?.disconnect(); + recordProcessorRef.current = null; + recordSilenceRef.current = null; setRecording(false); + + const { left, right } = recordChunksRef.current; + recordChunksRef.current = { left: [], right: [] }; + const totalFrames = left.reduce((sum, chunk) => sum + chunk.length, 0); + if (totalFrames === 0) return; + + const mergedLeft = new Float32Array(totalFrames); + const mergedRight = new Float32Array(totalFrames); + let offset = 0; + for (let i = 0; i < left.length; i++) { + mergedLeft.set(left[i], offset); + mergedRight.set(right[i], offset); + offset += left[i].length; + } + + const blob = encodeWavStereo(mergedLeft, mergedRight, audioContextRef.current?.sampleRate ?? SAMPLE_RATE); + const safeServerName = (serverName || "session").replace(/[\\/:*?"<>|]+/g, "_").trim() || "session"; + const filename = `webspeak3-${safeServerName}-${new Date().toISOString().replace(/[:.]/g, "-")}.wav`; + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + logClient("info", "Recording", `Saved recording as ${filename}`); }; const handleSetNickname = (newNickname: string) => { diff --git a/web/src/voice.ts b/web/src/voice.ts index d4976ad..d444fc5 100644 --- a/web/src/voice.ts +++ b/web/src/voice.ts @@ -171,6 +171,45 @@ export class MicCapture { } } +function writeAsciiString(view: DataView, offset: number, text: string): void { + for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i)); +} + +/** Encodes raw stereo float samples (range -1..1) as an uncompressed 16-bit PCM WAV file. */ +export function encodeWavStereo(left: Float32Array, right: Float32Array, sampleRate: number): Blob { + const numChannels = 2; + const bytesPerSample = 2; + const blockAlign = numChannels * bytesPerSample; + const dataSize = left.length * blockAlign; + const buffer = new ArrayBuffer(44 + dataSize); + const view = new DataView(buffer); + + writeAsciiString(view, 0, "RIFF"); + view.setUint32(4, 36 + dataSize, true); + writeAsciiString(view, 8, "WAVE"); + writeAsciiString(view, 12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); // PCM + view.setUint16(22, numChannels, true); + view.setUint32(24, sampleRate, true); + view.setUint32(28, sampleRate * blockAlign, true); + view.setUint16(32, blockAlign, true); + view.setUint16(34, 16, true); + writeAsciiString(view, 36, "data"); + view.setUint32(40, dataSize, true); + + let offset = 44; + for (let i = 0; i < left.length; i++) { + const l = Math.max(-1, Math.min(1, left[i])); + const r = Math.max(-1, Math.min(1, right[i])); + view.setInt16(offset, l < 0 ? l * 0x8000 : l * 0x7fff, true); + view.setInt16(offset + 2, r < 0 ? r * 0x8000 : r * 0x7fff, true); + offset += blockAlign; + } + + return new Blob([buffer], { type: "audio/wav" }); +} + /** Output ("audiooutput") devices available for playback, e.g. for a device picker. */ export async function listAudioOutputDevices(): Promise { if (!navigator.mediaDevices) return [];