I am working on a project where I want to continuously transmit audio over my server using Socket.io. Currently, users can send audio, but there is a delay because the function waits for the key to be unpressed before sending the audio to the server. As mentioned earlier, I am using Socket.io along with JavaScript and Node.js for this project.
Here is the current code:
const socket = io();
const audioElement = document.getElementById('audioElement');
let isPushed = false;
let mediaRecorder;
let chunks = [];
// Request access to the user's microphone
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
// Create a MediaRecorder to record audio chunks
mediaRecorder = new MediaRecorder(stream);
// Handle data available event to collect audio chunks
mediaRecorder.addEventListener('dataavailable', event => {
chunks.push(event.data);
// Send the audio chunk to the server immediately
socket.emit('voiceMessage', event.data);
});
// Handle stop event to stop recording
mediaRecorder.addEventListener('stop', () => {
// Stop the recording and reset the chunks
mediaRecorder.stop();
chunks = [];
});
// Add an event listener to detect the 'N' key press
document.addEventListener('keydown', (event) => {
if (event.key === 'n' || event.key === 'N') {
if (!isPushed) {
document.getElementById('tpt1').play();
mediaRecorder.start();
isPushed = true;
}
}
});
// Add an event listener to detect the 'N' key release
document.addEventListener('keyup', (event) => {
if (event.key === 'n' || event.key === 'N') {
if (isPushed) {
setTimeout(() => {
document.getElementById('tpt2').play();
mediaRecorder.stop();
isPushed = false;
}, 250); // Add a 500 ms (half-second) delay
}
}
});
})
.catch(error => {
console.error('Error accessing microphone:', error);
});
// Handle receiving voice messages from the server
socket.on('voiceMessage', (audioBlob) => {
const audioURL = URL.createObjectURL(new Blob([audioBlob], { type: 'audio/webm;codecs:vorbis' }));
const audioElement = new Audio(audioURL);
audioElement.controls = true;
document.body.appendChild(audioElement);
audioElement.play();
});
I was expecting it to send the audio over the server immediately after starting the media record. If more information is needed to assist me, I will be happy to send it over! Thanks in advance!