Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sending live audio recording to backend

I am trying to send the live chunks of audio being recorded on a browser to my node js server using socket io. What I have tried so far only sends the buffer when I stop mediaRecorder but what I want to achieve is to send the live chucks every certain kilobyte. How can I achieve this?

const socket = io();

const recordButton = document.getElementById('record');
const stopButton = document.getElementById('stop_rec');

let userId;

socket.on('connect', () => {
  userId = socket.id

  socket.on(userId, (msg) => {
    console.log('Message from server:', msg);
  });

  recordButton.addEventListener('click', async() => {
    audioStream()
  });

  stopButton.addEventListener('click', () => {
    doneSpeaking()
  });
});

let mediaRecorder;

async function audioStream() {
  try {
    const constraints = {
      audio: {
        sampleRate: 16000,
        channelCount: 1
      }
    };
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    mediaRecorder = new MediaRecorder(stream);

    mediaRecorder.start();

    const handleDataAvailable = (e) => {
      //this sends the buffer to server after I stop mediaRecorder
      socket.emit(userId, e.data);
    };

    mediaRecorder.ondataavailable = handleDataAvailable;

    mediaRecorder.onstop = () => {
      console.log('Recording stopped');
    };
  } catch (error) {
    console.error('Error accessing microphone:', error);
  }
}

function doneSpeaking() {
  if (mediaRecorder && mediaRecorder.state === 'recording') {
    mediaRecorder.stop(); // Stop the recording
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The docs for MediaRecorder state:

dataavailable

Fires periodically each time timeslice milliseconds of media have been recorded (or when the entire media has been recorded, if timeslice wasn’t specified).

You can specify it in the start method of MediaRecorder:

mediaRecorder.start(1000); // sends data every second
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading