mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 01:42:50 +08:00
Save local recordings as WAV instead of webm
Swaps the MediaRecorder-based capture for a raw PCM tap (ScriptProcessorNode) and a hand-rolled WAV encoder, since MediaRecorder's output format/codec is browser-dependent (webm/opus) and the user wants a plain, universally compatible file. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
67c4bc1072
commit
284645f18d
2 files changed
+99
-35
No files matched your search
+60
-35
@@ -18,6 +18,7 @@ import {
|
|||||||
AudioPlayer,
|
AudioPlayer,
|
||||||
MicCapture,
|
MicCapture,
|
||||||
SAMPLE_RATE,
|
SAMPLE_RATE,
|
||||||
|
encodeWavStereo,
|
||||||
hasNativeOutputPicker,
|
hasNativeOutputPicker,
|
||||||
listAudioInputDevices,
|
listAudioInputDevices,
|
||||||
listAudioOutputDevices,
|
listAudioOutputDevices,
|
||||||
@@ -2068,9 +2069,9 @@ function AppInner() {
|
|||||||
const audioContextRef = useRef<AudioContext | null>(null);
|
const audioContextRef = useRef<AudioContext | null>(null);
|
||||||
const audioPlayerRef = useRef<AudioPlayer | null>(null);
|
const audioPlayerRef = useRef<AudioPlayer | null>(null);
|
||||||
const micCaptureRef = useRef<MicCapture | null>(null);
|
const micCaptureRef = useRef<MicCapture | null>(null);
|
||||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
const recordProcessorRef = useRef<ScriptProcessorNode | null>(null);
|
||||||
const recordDestRef = useRef<MediaStreamAudioDestinationNode | null>(null);
|
const recordSilenceRef = useRef<GainNode | null>(null);
|
||||||
const recordedChunksRef = useRef<Blob[]>([]);
|
const recordChunksRef = useRef<{ left: Float32Array[]; right: Float32Array[] }>({ left: [], right: [] });
|
||||||
const activeTabRef = useRef<ActiveTab>("channel");
|
const activeTabRef = useRef<ActiveTab>("channel");
|
||||||
const hasConnectedRef = useRef(false);
|
const hasConnectedRef = useRef(false);
|
||||||
// Set when a "disconnected" event is received, so the socket's onclose
|
// 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
|
// 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.
|
// switch or a mic (re)start mid-recording doesn't silently drop it from the mix.
|
||||||
const connectMicToRecorder = () => {
|
const connectMicToRecorder = () => {
|
||||||
const dest = recordDestRef.current;
|
const processor = recordProcessorRef.current;
|
||||||
const source = micCaptureRef.current?.getSourceNode();
|
const source = micCaptureRef.current?.getSourceNode();
|
||||||
if (dest && source) source.connect(dest);
|
if (processor && source) source.connect(processor);
|
||||||
};
|
};
|
||||||
|
|
||||||
const startRecording = () => {
|
const startRecording = () => {
|
||||||
if (recorderRef.current) return;
|
if (recordProcessorRef.current) return;
|
||||||
const audioContext = ensureAudioContext();
|
const audioContext = ensureAudioContext();
|
||||||
const dest = audioContext.createMediaStreamDestination();
|
// Captures raw PCM via a ScriptProcessorNode (rather than MediaRecorder) so the
|
||||||
recordDestRef.current = dest;
|
// download can be an uncompressed WAV instead of a browser-codec-dependent webm/ogg.
|
||||||
audioPlayerRef.current?.getInputNode().connect(dest);
|
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();
|
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);
|
setRecording(true);
|
||||||
logClient("info", "Recording", "Started local recording");
|
logClient("info", "Recording", "Started local recording");
|
||||||
};
|
};
|
||||||
|
|
||||||
const stopRecording = () => {
|
const stopRecording = () => {
|
||||||
recorderRef.current?.stop();
|
const processor = recordProcessorRef.current;
|
||||||
recorderRef.current = null;
|
if (!processor) return;
|
||||||
recordDestRef.current = null;
|
processor.onaudioprocess = null;
|
||||||
|
processor.disconnect();
|
||||||
|
recordSilenceRef.current?.disconnect();
|
||||||
|
recordProcessorRef.current = null;
|
||||||
|
recordSilenceRef.current = null;
|
||||||
setRecording(false);
|
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) => {
|
const handleSetNickname = (newNickname: string) => {
|
||||||
|
|||||||
@@ -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. */
|
/** Output ("audiooutput") devices available for playback, e.g. for a device picker. */
|
||||||
export async function listAudioOutputDevices(): Promise<MediaDeviceInfo[]> {
|
export async function listAudioOutputDevices(): Promise<MediaDeviceInfo[]> {
|
||||||
if (!navigator.mediaDevices) return [];
|
if (!navigator.mediaDevices) return [];
|
||||||
|
|||||||
Reference in new issue
Block a user