2

I know this is a common question, but for some reason, there are several answers (which confuses me)

tl;dr I am trying to set a button that let you record yourself for up to 10 seconds (you can press stop if you want to stop recording before) and then let you play it.


What I have tried till now :

I know there is the library getUserMedia, and I have (tried) created a MediaStream. I get confused when it comes to the Recording itself and the.Start() and Stop()

here is my code for getting the user`s permission to access the microphone :

const getmiceacesses = function () {
const stream = navigator.mediaDevices
.getUserMedia({ audio: true })
.then(function (stream) {const mediaRecorder = new MediaRecorder(stream);
  const audioChunks = [];

  mediaRecorder.addEventListener("dataavailable", (event) => {
    audioChunks.push(event.data);
  });
});};

const recording = document.querySelector(`.recorder`);
recording.addEventListener(`click`, getmiceacesses);

Thank you guys!

  • Welcome to StackOverflow! Please read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Rojo Aug 11 '21 at 23:12
  • Does this answer your question? [How to capture audio in javascript?](https://stackoverflow.com/questions/34820578/how-to-capture-audio-in-javascript) – Tangentially Perpendicular Aug 11 '21 at 23:31
  • @TangentiallyPerpendicular I don't get the usage, and how to use it. And if there is any way to explain the code itself, I want to fully understand the code and he doesn't provide actual explanation :/ – JavaScripter Aug 11 '21 at 23:50

1 Answers1

1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <audio id='audioPlayer'></audio>

    <button type="button" class="recorder">Start</button>
    <button type="button" class="stopRecorder">Stop</button>
    
    <script>
        function playAudio(audioChunks) {
          const blob = new Blob(audioChunks,{type:'audio/x-mpeg-3'});
          const audioPlayer = document.getElementById('audioPlayer')
          audioPlayer.src = URL.createObjectURL(blob);
          audioPlayer.controls=true;
          audioPlayer.autoplay=true;
        }

       var mediaRecorder; // Need to be accessible for the stopRecorder function
       const audioChunks = []; // Place it here to debug it contents after finsih recording

        const getmiceacesses = function () {
        const stream = navigator.mediaDevices.getUserMedia({ audio: true })
        .then(function (stream) {
            mediaRecorder = new MediaRecorder(stream);
 
             mediaRecorder.start();

             setTimeout(stopRecorder, 10000) // To automatically stop the recorder after 10 seconds
 
            mediaRecorder.addEventListener("dataavailable", (event) => {
                audioChunks.push(event.data);
                playAudio(audioChunks)
                console.log('Debugging Breakpoint')
            });
        })
      ;};

             
     const stopRecorder = function(){
         if(mediaRecorder.state === 'recording'){
            mediaRecorder.stop();
         }
     }

     const recording = document.querySelector('.recorder');
     recording.addEventListener('click', getmiceacesses);

     const stopRecording = document.querySelector('.stopRecorder');
     stopRecording.addEventListener('click', stopRecorder);
    </script>
</body>
</html>
ManuelMB
  • 1,254
  • 2
  • 8
  • 16
  • it works! thank you so much ! can I use it for a project I am publishing ? and btw do you mind explaining it a bit :)? – JavaScripter Aug 12 '21 at 00:18
  • The start button call the getmiceacesses function, this function create a MediaRecorder Object (The MediaRecorder interface of the MediaStream Recording API provides functionality to easily record media.) and start the recording. The setTimeout function call the stopRecorder after 10 seconds (Always can be stoped previously by clicking the Stop button). When the stopRecorder function is called we check if the mediaRecorder is recording and if so, we stop recording by calling the mediaRecorder.stop() function. – ManuelMB Aug 12 '21 at 00:32
  • When this function is called the dataavailable EventListener is called and the Datais added to the audioChunks Array. – ManuelMB Aug 12 '21 at 00:34
  • great got it! thanks! Can I use this code for my project? any license or something? and btw - to check if the user rejected the accesses I can just add an if statement in the beginning right? – JavaScripter Aug 12 '21 at 01:01