I'm trying to build a simple audio recorder that records and plays the users voice at the same time ( synchronously ) using WebRTC and MediaRecorder. So, here is what I've done so far :
Full Html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Audio Recorder</title>
<style>
audio{
display: block;
}
</style>
</head>
<body>
<audio id="audio" controls autoplay></audio>
<button type="button" onclick="mediaRecorder.start(1000)">Start</button>
<button type="button" onclick="mediaRecorder.stop()">Stop</button>
<script type="text/javascript">
var mediaRecorder = null,
chunks = [],
audio = document.getElementById('audio');
function onSuccess( stream ) {
mediaRecorder = new MediaRecorder( stream );
audio.srcObject = stream ;
mediaRecorder.ondataavailable = function( event ) {
chunks.push( event.data );
}
}
var onError = function(err) {
console.log('Error: ' + err);
}
navigator.mediaDevices.getUserMedia({ audio: true }).then(onSuccess, onError);
</script>
</body>
</html>
The problem with this code is that, it plays the whole stream, and what I want is the recorded part only ( the audio recorded by the MediaRecorder ).
Question: Is that possible or the only option is stopping the recorder and then getting the recorded part ( 'chunks' in the code ) ?
Note: A yes/no answer would be more than enough for me. Thanks.
Code explanation :
When you run the code, your browser asks you for permission to access your microphone :
In case, you hit allow, you will hear your voice even if you didn't click the start button, and that's because the source of the audio element is set to the whole stream .
What I want is to hear the recorded part only, when recording ( hitting the start button ), in other words, converting the recorded part into a stream.
What I'm looking for :
Just remove autoplay
from your audio element, and do
mediaRecorder.start(1000);
audio.play();
and
mediaRecorder.stop();
audio.pause();
Then audio from the microphone will be audible during recording only.
You don't need to convert the recorded part to a stream. If you did, it would just introduce a delay.
OTOH, if you're trying to play back what you've already recorded, see my answer to another question.
The answer is negative. Using stream as audio.srcObject does not provide the necessary flexibility to limit audio.duration. You must use a Blob of chunks to achieve this.
The MediaRecorder works in chunks (even if you don't set the chunk duration in mediaRecorder.start(), hence there is no way to reliably produce audio of exact duration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With