Middle
How was voice message sending implemented in chat? How did you get permission to access the microphone?
sobes.tech AI
Answer from AI
To implement sending voice messages in a chat, Web Audio API and MediaRecorder API are usually used.
- Getting permission to access the microphone:
The method navigator.mediaDevices.getUserMedia({ audio: true }) is used, which requests permission from the user to use the microphone. If the user grants permission, an audio stream is returned.
async function getMicrophoneAccess() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
return stream;
} catch (err) {
console.error('Microphone access denied', err);
return null;
}
}
- Recording audio:
Using MediaRecorder, you can record audio from the obtained stream. For example:
const stream = await getMicrophoneAccess();
if (stream) {
const mediaRecorder = new MediaRecorder(stream);
const chunks = [];
mediaRecorder.ondataavailable = e => chunks.push(e.data);
mediaRecorder.onstop = () => {
const audioBlob = new Blob(chunks, { type: 'audio/webm' });
// Send audioBlob to server or play it
};
mediaRecorder.start();
// Stop recording after some time
setTimeout(() => mediaRecorder.stop(), 5000);
}
- Sending voice message:
After recording audio into a Blob, it can be sent to the server via fetch or WebSocket, and then played for the recipient.
Thus, the key steps are requesting permission via getUserMedia, recording via MediaRecorder, and transmitting audio data.