return {
isRecording,
startRecording,
stopRecording,
};
}''' add the wav headers to chunks (except the first one ) '' dataView.setUint32(0, textAsUint32('RIFF'));'' The first 44 bytes of the first chunk contain that header
Assistant
To add WAV headers to the audio chunks generated by your useAudioRecorder hook, you'll need to modify the handling of the audio data within the ondataavailable event. Specifically, you'll add a WAV header to the first chunk and ensure that subsequent chunks do not include additional headers.
Here's the updated code with detailed comments explaining each step:
typescript
import { useCallback, useRef, useState } from 'react';
import { AudioConfig } from '../types';
const DEFAULT_AUDIO_CONFIG: AudioConfig = {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 44100,
};
// Helper function to convert string to Uint32
const textAsUint32 = (text: string) => {
const buf = new ArrayBuffer(4);
const view = new DataView(buf);
for (let i = 0; i < Math.min(text.length, 4); i++) {
view.setUint8(i, text.charCodeAt(i));
}
return view.getUint32(0, true);
};
// Helper function to create WAV header
const createWavHeader = (dataSize: number, sampleRate: number, numChannels: number, bitsPerSample: number) => {
const buffer = new ArrayBuffer(44);
const view = new DataView(buffer);
// RIFF identifier
view.setUint32(0, textAsUint32('RIFF'), true);
// Overall file size minus first 8 bytes
view.setUint32(4, 36 + dataSize, true);
// WAV identifier
view.setUint32(8, textAsUint32('WAVE'), true);
//fmt chunk identifier
view.setUint32(12, textAsUint32('fmt '), true);
//fmt chunk length
view.setUint32(16, 16, true);
// Audio format (1 = PCM)
view.setUint16(20, 1, true);
// Number of channels
view.setUint16(22, numChannels, true);
// Sample rate
view.setUint32(24, sampleRate, true);
// Byte rate (Sample Rate * Num Channels * Bits per Sample / 8)
view.setUint32(28, sampleRate * numChannels * bitsPerSample / 8, true);
// Block align (Num Channels * Bits per Sample / 8)
view.setUint16(32, numChannels * bitsPerSample / 8, true);
// Bits per sample
view.setUint16(34, bitsPerSample, true);
//data chunk identifier
view.setUint32(36, textAsUint32('data'), true);
//data chunk length
view.setUint32(40, dataSize, true);
return new Uint8Array(buffer);
};
export function useAudioRecorder(onAudioChunk: (blob: Blob) => Promise<void>) {
const [isRecording, setIsRecording] = useState(false);
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const streamRef = useRef<MediaStream | null>(null);
// Ref to track if it's the first chunk
const isFirstChunkRef = useRef(true);
// Variable to accumulate audio data size for WAV header
const audioDataSizeRef = useRef(0);
const startRecording = useCallback(async () => {
try {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: DEFAULT_AUDIO_CONFIG,
});
const audioTrack = stream.getAudioTracks()[0];
if (!audioTrack) {
throw new Error('No audio track found in the shared content');
}
const audioStream = new MediaStream([audioTrack]);
streamRef.current = stream;
const mediaRecorder = new MediaRecorder(audioStream, {
mimeType: 'audio/webm', // You might need to adjust MIME type based on browser support
});
mediaRecorderRef.current = mediaRecorder;
mediaRecorder.ondataavailable = async (e) => {
if (e.data.size > 0) {
const arrayBuffer = await e.data.arrayBuffer();
if (isFirstChunkRef.current) {
isFirstChunkRef.current = false;
// Update `audioDataSizeRef` with the size of audio data
audioDataSizeRef.current += arrayBuffer.byteLength;
// Create WAV header
const wavHeader = createWavHeader(arrayBuffer.byteLength, DEFAULT_AUDIO_CONFIG.sampleRate, 1, 16); // Assuming 16 bits per sample
// Combine WAV header and audio data
const combinedBuffer = new Uint8Array(wavHeader.byteLength + arrayBuffer.byteLength);
combinedBuffer.set(wavHeader, 0);
combinedBuffer.set(new Uint8Array(arrayBuffer), wavHeader.byteLength);
await onAudioChunk(new Blob([combinedBuffer], { type: 'audio/wav' }));
} else {
// For subsequent chunks, just append the raw audio data
await onAudioChunk(new Blob([arrayBuffer], { type: 'audio/wav' }));
}
// Update total audio data size
audioDataSizeRef.current += arrayBuffer.byteLength;
}
};
mediaRecorder.start(3000); // Emit data every 3 seconds
setIsRecording(true);
} catch (error) {
console.error('Error starting recording:', error);
throw new Error('Failed to start recording');
}
}, [onAudioChunk]);
const stopRecording = useCallback(() => {
if (mediaRecorderRef.current && isRecording) {
mediaRecorderRef.current.stop();
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop());
}
setIsRecording(false);
// Reset the chunk tracker
isFirstChunkRef.current = true;
audioDataSizeRef.current = 0;
}
}, [isRecording]);
return {
isRecording,
startRecording,
stopRecording,
};
}
Explanation of Changes:
WAV Header Creation:
createWavHeader Function: This helper function constructs a WAV file header based on the audio data size, sample rate, number of channels, and bits per sample. The header is 44 bytes long, which is standard for WAV files.
textAsUint32 Function: Converts a 4-character string (like 'RIFF' or 'WAVE') to a Uint32 value, which is written into the WAV header.
Tracking Chunks:
isFirstChunkRef: A useRef hook is used to track whether the current chunk is the first one. This ensures that the WAV header is only added to the first chunk.
audioDataSizeRef: Keeps track of the total size of the audio data. This is useful if you need to adjust the WAV header dynamically based on the total size, but in this simplified example, it's primarily for demonstration.
Modifying the ondataavailable Handler:
First Chunk (isFirstChunkRef.current === true):
Creates a WAV header using the createWavHeader function.
Combines the WAV header with the first chunk of audio data.
Passes the combined data as a Blob with the MIME type 'audio/wav' to the onAudioChunk callback.
Subsequent Chunks:
Passes only the raw audio data without any additional headers.
Continues to use the MIME type 'audio/wav' for consistency, but note that the subsequent chunks don't contain valid WAV headers, which might affect how they're processed downstream.
Resetting State on Stop:
When stopRecording is called, it resets isFirstChunkRef and audioDataSizeRef to ensure that a new recording session starts fresh.
Important Considerations:
WAV File Structure: WAV headers typically include metadata like the total file size, which isn't known until all audio data is captured. This example appends the header only to the first chunk, which might not produce a valid WAV file if played as a single file. For proper WAV file generation, you might need to wait until all chunks are recorded, calculate the total size, and then prepend the header.
MIME Type: The MediaRecorder uses 'audio/webm' in the original code. If you're switching to WAV, ensure that the browser supports recording in WAV format, or consider post-processing the recorded data to convert it to WAV.
Error Handling: Ensure that your onAudioChunk callback can handle the different chunk formats, especially if only the first chunk contains the WAV header.
Browser Compatibility: Not all browsers may support the MIME types and features used. Always check for compatibility and provide fallbacks if necessary.
By implementing these changes, your useAudioRecorder hook will add a WAV header to the first audio chunk, enabling the subsequent data to be interpreted as a WAV file stream.