try {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: {
...DEFAULT_AUDIO_CONFIG,
channelCount: 1, // Mono audio (preferred by Whisper)
},
});
const audioTrack = stream.getAudioTracks()[0];
if (!audioTrack) {
throw new Error('No audio track found in the shared content');
}
// Create audio context to handle sample rate conversion if needed
const audioContext = new AudioContext({
sampleRate: DEFAULT_AUDIO_CONFIG.sampleRate,
});
// Create media stream source
const sourceNode = audioContext.createMediaStreamSource(new MediaStream([audioTrack]));
// Create script processor for potential sample rate conversion
const processor = audioContext.createScriptProcessor(4096, 1, 1);
// Connect the nodes
sourceNode.connect(processor);
processor.connect(audioContext.destination);
// Create a new stream with the processed audio
const audioStream = new MediaStream([audioTrack]);
streamRef.current = stream;
// Clear previous chunks
chunksRef.current = [];
const mediaRecorder = new MediaRecorder(audioStream, {
mimeType: getSupportedMimeType(),
});
mediaRecorderRef.current = mediaRecorder;
let i=0;
mediaRecorder.ondataavailable = async (e) => {
if (e.data.size > 0) {
chunksRef.current.push(e.data);
try {
const blobUrl = URL.createObjectURL(e.data);
const a = document.createElement('a');
a.style.display = 'none';
a.href = blobUrl;
a.download = `audio_chunk_${i++}.webm`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(blobUrl);
await onAudioChunk(e.data);
} catch (error) {
console.error('Error processing audio chunk:', error);
}
}
};
mediaRecorder.onerror = (event) => {
console.error('MediaRecorder error:', event);
stopRecording();
};
// Handle stream stop event
stream.getTracks().forEach(track => {
track.onended = () => {
stopRecording();
};
});
mediaRecorder.start(3000); // Create chunks every 3 seconds
setIsRecording(true);
// Cleanup function for audio context
return () => {
processor.disconnect();
sourceNode.disconnect();
audioContext.close();
};
} catch (error) {
console.error('Error starting recording:', error);
throw new Error('Failed to start recording');
}
}, [onAudioChunk]);
// Function to get the complete recording
const getCompleteRecording = useCallback(async (): Promise => {
if (chunksRef.current.length === 0) {
throw new Error('No recording available');
}
return new Blob(chunksRef.current, { type: getSupportedMimeType() });
}, []);
const stopRecording = useCallback(async () => {
if (mediaRecorderRef.current && isRecording) {
try {
// Request the final chunk
mediaRecorderRef.current.requestData();
code
// Stop the media recorder
mediaRecorderRef.current.stop();
// Stop all tracks in the stream
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop());
streamRef.current = null;
}
// Get the complete recording before clearing
const finalRecording = await getCompleteRecording();
// Reset the media recorder and chunks
mediaRecorderRef.current = null;
chunksRef.current = [];
setIsRecording(false);
return finalRecording;
} catch (error) {
console.error('Error stopping recording:', error);
throw error;
}
}
To enhance your audio recording functionality by incorporating a JavaScript library for handling audio chunks, you can integrate RecordRTC. RecordRTC offers a more flexible and feature-rich API compared to the native MediaRecorder, allowing enhanced control over audio recording, chunk management, and encoding.
Here's how you can update your existing useAudioRecorder hook to integrate RecordRTC for handling audio chunks:
Step 1: Install RecordRTC
First, you need to install the recordrtc library. You can do this using npm or yarn:
bash
npm install recordrtc
or
bash
yarn add recordrtc
Step 2: Update the useAudioRecorder Hook
Below is the updated code for your useAudioRecorder hook that integrates RecordRTC to handle audio chunks effectively:
tsx
import { useCallback, useRef, useState } from 'react';
import RecordRTC, { RecordRTCPromisesHandler } from 'recordrtc';
interface AudioConfig {
echoCancellation: boolean;
noiseSuppression: boolean;
sampleRate: number;
}
const DEFAULT_AUDIO_CONFIG: AudioConfig = {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 16000, // Whisper works best with 16kHz sample rate
};
export function useAudioRecorder(onAudioChunk: (blob: Blob) => Promise<void>) {
const [isRecording, setIsRecording] = useState(false);
const recorderRef = useRef<RecordRTCPromisesHandler | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const chunksRef = useRef<Blob[]>([]);
const chunkIntervalRef = useRef<NodeJS.Timeout | null>(null);
const chunkIndexRef = useRef<number>(0);
const startRecording = useCallback(async () => {
try {
// Request microphone access with the desired audio constraints
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
...DEFAULT_AUDIO_CONFIG,
channelCount: 1, // Mono audio (preferred by Whisper)
},
});
streamRef.current = stream;
// Initialize RecordRTC with the stream and desired options
const recorder = new RecordRTC(stream, {
type: 'audio',
mimeType: 'audio/webm;codecs=opus', // Specify MIME type for compatibility
sampleRate: DEFAULT_AUDIO_CONFIG.sampleRate,
numberOfAudioChannels: 1,
bufferSize: 4096, // Buffer size for processing
ondataavailable: async (blob: Blob) => {
if (blob.size > 0) {
chunksRef.current.push(blob);
try {
// Optional: Download each chunk (for debugging or storage)
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = blobUrl;
a.download = `audio_chunk_${chunkIndexRef.current++}.webm`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(blobUrl);
// Process the audio chunk via the callback
await onAudioChunk(blob);
} catch (error) {
console.error('Error processing audio chunk:', error);
}
}
},
});
recorderRef.current = recorder;
// Start recording
await recorder.startRecording();
setIsRecording(true);
// Periodically request audio data to simulate chunking
chunkIntervalRef.current = setInterval(async () => {
if (recorder && recorder.getState() === 'recording') {
await recorder.requestData();
}
}, 3000); // Create chunks every 3 seconds
// Handle stream stop
stream.getAudioTracks().forEach(track => {
track.onended = () => {
stopRecording();
};
});
} catch (error) {
console.error('Error starting recording:', error);
throw new Error('Failed to start recording');
}
}, [onAudioChunk]);
// Function to get the complete recording
const getCompleteRecording = useCallback(async (): Promise<Blob> => {
if (chunksRef.current.length === 0) {
throw new Error('No recording available');
}
return new Blob(chunksRef.current, { type: 'audio/webm;codecs=opus' });
}, []);
const stopRecording = useCallback(async () => {
if (recorderRef.current && isRecording) {
try {
// Clear the interval that requests data
if (chunkIntervalRef.current) {
clearInterval(chunkIntervalRef.current);
chunkIntervalRef.current = null;
}
// Stop recording and retrieve any remaining audio data
await recorderRef.current.stopRecording();
// Stop all media tracks to release resources
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop());
streamRef.current = null;
}
// Get the complete recording before clearing
const finalRecording = await getCompleteRecording();
// Reset the recorder and chunks
recorderRef.current = null;
chunksRef.current = [];
chunkIndexRef.current = 0;
setIsRecording(false);
return finalRecording;
} catch (error) {
console.error('Error stopping recording:', error);
throw error;
}
}
}, [isRecording, getCompleteRecording]);
return {
isRecording,
startRecording,
stopRecording,
getCompleteRecording,
};
}
Step 3: Explanation of Changes
Importing RecordRTC:
tsx
import RecordRTC, { RecordRTCPromisesHandler } from 'recordrtc';
RecordRTC is imported to manage the audio recording process with enhanced capabilities.
RecordRTC is built on top of MediaRecorder and other Web APIs, so ensure that the target browsers support the necessary features. Most modern browsers have good support, but always verify compatibility for your user base.
Handling Different MIME Types:
Depending on your use case, you may need to adjust the mimeType. Ensure that the chosen MIME type is supported by the browser and suits your backend processing requirements.
Error Handling:
Enhance error handling as needed, especially around permissions and stream management, to provide a better user experience.
Performance Optimization:
Fine-tune the bufferSize and chunk intervals based on the performance and latency requirements of your application.
Security Considerations:
Always handle media streams securely, ensure HTTPS is used, and manage permissions appropriately to protect user privacy.
Testing:
Thoroughly test the recording functionality across different devices and browsers to ensure reliability and performance.
Conclusion
By integrating RecordRTC into your useAudioRecorder hook, you gain enhanced control over audio recording and chunk management. RecordRTC simplifies handling audio chunks, provides better compatibility options, and offers a more robust API for complex recording scenarios. This integration will make your audio recording feature more reliable and easier to maintain, especially when dealing with processing audio chunks for tasks like transcription with Whisper.