Skip to content

Instantly share code, notes, and snippets.

@TheLarkInn
Last active January 31, 2019 15:29
Show Gist options
  • Save TheLarkInn/672f8e37b84dc4ff96f6db559605477f to your computer and use it in GitHub Desktop.
Save TheLarkInn/672f8e37b84dc4ff96f6db559605477f to your computer and use it in GitHub Desktop.
Record that voice! Just learning MediaRecorder API's
const captureWebRTCAudio = (successHandler) => {
return navigator.mediaDevices.getUserMedia({audio: true, video: false}).then(successHandler);
};
export default captureWebRTCAudio;
import captureWebRTCAudio from "./captureWebRTCAudio";
import saveAudioStream from "./saveAudioStream";
const recordEl = document.createElement("button");
const stopEl = document.createElement("button");
recordEl.innerText = "Record";
stopEl.innerText = "Stop";
document.body.appendChild(recordEl);
document.body.appendChild(stopEl);
captureWebRTCAudio((stream) => {
saveAudioStream(stream, recordEl, stopEl);
})
/**
*
* @param {string} idString
* @returns {HTMLAudioElement}
*/
const makeAudioPlayer = (idString) => {
const playerEl = document.createElement("audio");
playerEl.setAttribute("controls", "");
playerEl.id = idString;
return playerEl;
}
export default makeAudioPlayer;
import makeAudioPlayer from "./makeAudioPlayer";
/**
*
* @param {MediaStream} stream
* @param {HTMLButtonElement} recordEl
* @param {HTMLButtonElement} stopEl
*/
const saveAudioStream = (stream, recordEl, stopEl) => {
let chunks = [];
const mediaRecorder = new MediaRecorder(stream);
recordEl.addEventListener("click", (event) => {
mediaRecorder.start();
recordEl.style.background = "red";
stopEl.disabled = false;
recordEl.disabled = true;
});
stopEl.addEventListener("click", (event) => {
mediaRecorder.stop();
recordEl.style.background = "";
recordEl.style.color = "";
stopEl.disabled = true;
recordEl.disabled = false;
});
mediaRecorder.addEventListener("stop", (event) => {
const clipContainer = document.createElement('article');
const clipLabel = document.createElement('p');
const audio = makeAudioPlayer('play');
document.body.appendChild(clipContainer);
clipContainer.appendChild(audio);
clipContainer.appendChild(clipLabel);
audio.controls = true;
const blob = new Blob(chunks, {'type': 'audio/ogg; codecs=opus'});
chunks = [];
const audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
});
mediaRecorder.addEventListener("dataavailable", (event) => {
chunks.push(event.data);
});
};
export default saveAudioStream
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment