Created
October 7, 2018 16:56
-
-
Save bryanjenningz/fb73b85af6a142529ef6861b6e0bc263 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<button onclick="record()">Record</button> | |
<script> | |
const recordAudio = () => | |
new Promise(async resolve => { | |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
const mediaRecorder = new MediaRecorder(stream); | |
const audioChunks = []; | |
mediaRecorder.addEventListener("dataavailable", event => { | |
audioChunks.push(event.data); | |
}); | |
const start = () => mediaRecorder.start(); | |
const stop = () => | |
new Promise(resolve => { | |
mediaRecorder.addEventListener("stop", () => { | |
// audioChunks will be filled at this point because the "stop" event happened | |
console.log(2, JSON.stringify(audioChunks)); | |
const audioBlob = new Blob(audioChunks); | |
const audioUrl = URL.createObjectURL(audioBlob); | |
const audio = new Audio(audioUrl); | |
const play = () => audio.play(); | |
resolve({ audioBlob, audioUrl, play }); | |
}); | |
mediaRecorder.stop(); | |
// audioChunks will be empty at this point | |
console.log(1, JSON.stringify(audioChunks)); | |
}); | |
resolve({ start, stop }); | |
}); | |
const sleep = time => new Promise(resolve => setTimeout(resolve, time)); | |
const record = async () => { | |
const recorder = await recordAudio(); | |
recorder.start(); | |
await sleep(3000); | |
const audio = await recorder.stop(); | |
audio.play(); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment