Skip to content

Instantly share code, notes, and snippets.

@alexcohn
Created May 9, 2018 18:32
Show Gist options
  • Save alexcohn/a8e6cd0cc88ada7e1387b2f1545b8476 to your computer and use it in GitHub Desktop.
Save alexcohn/a8e6cd0cc88ada7e1387b2f1545b8476 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Audio Recorder</title>
<style>
audio {
display: block;
}
</style>
</head>
<body>
<button type="button" onclick="mediaRecorder.start(1000)">Start</button>
<button type="button" onclick="mediaRecorder.stop()">Stop</button>
<script type="text/javascript">
var mediaRecorder = null,
audio = null,
chunks = [],
startTs = 0,
timeout = null,
max_duration = 4;// in seconds.
function onSuccess( stream ) {
mediaRecorder = new MediaRecorder( stream );
mediaRecorder.ondataavailable = function( event ) {
document.body.insertAdjacentHTML( 'beforeend', 'add chunk #' + chunks.length + ' at ' + (Date.now()-startTs) + ' ' + event.data.size + ' bytes <br/>' );
chunks.push( event.data )
if ( chunks.length >= max_duration && mediaRecorder.state === 'recording' ) {
document.body.insertAdjacentHTML( 'beforeend', 'stop ' + (Date.now()-startTs) + '<br/>' )
mediaRecorder.stop()
}
}
mediaRecorder.onstart = function() {
startTs = Date.now()
document.body.insertAdjacentHTML( 'beforeend', '<br/>start <br/>' )
setTimeout(function() {
if ( mediaRecorder.state === 'recording' ) {
document.body.insertAdjacentHTML( 'beforeend', 'timeout ' + (Date.now()-startTs) + '<br/>' )
stream.getAudioTracks()[0].enabled = false
}
}, max_duration*1000)
};
mediaRecorder.onstop = function() {
audio = document.createElement('audio')
audio_blob = new Blob(chunks, {
'type' : 'audio/mpeg'
})
audio.controls = 'controls'
audio.autoplay = 'autoplay'
audio.src = URL.createObjectURL( audio_blob )
setTimeout(function() {
if (audio.parent == null ) {
document.body.appendChild(audio)
}
}, 5000);
startTs = Date.now()
timeout = setInterval(function() {
if (Number.isFinite(audio.duration)) {
document.body.insertAdjacentHTML( 'beforeend', '<br/>duration ' + audio.duration + ' calculated in ' + (Date.now()-startTs) + ' for ' + chunks.length + ' chunks <br/>' )
if ( Math.floor(audio.duration) > max_duration - 2 && audio.parent == null ) {
chunks = chunks.slice(0, chunks.length-1)
shorter_audio_blob = new Blob(chunks, {
'type' : 'audio/mpeg'
})
audio.src = URL.createObjectURL( shorter_audio_blob )
}
else {
clearInterval(timeout)
document.body.appendChild(audio);
}
}
}, 10) // it takes some time for duration to become valid
}
}
var onError = function(err) {
console.log('Error: ' + err)
}
navigator.mediaDevices.getUserMedia({ audio: true }).then(onSuccess, onError)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment