Last active
September 5, 2023 12:22
-
-
Save tatsuyasusukida/ec7f682629171b420726099451992c02 to your computer and use it in GitHub Desktop.
🎤 How to record audio using the MediaStream Recording API in JavaScript
This file contains 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
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>How to record audio using the MediaStream Recording API in JavaScript</title> | |
</head> | |
<body> | |
<h1>How to record audio using the MediaStream Recording API in JavaScript</h1> | |
<div> | |
<button type="button" id="buttonStart">Start</button> | |
<button type="button" id="buttonStop" disabled>Stop</button> | |
</div> | |
<div> | |
<audio controls id="player"></audio> | |
</div> | |
<script src="main.js"></script> | |
</body> | |
</html> |
This file contains 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
main() | |
async function main () { | |
const buttonStart = document.querySelector('#buttonStart') | |
const buttonStop = document.querySelector('#buttonStop') | |
const player = document.querySelector('#player') | |
const stream = await navigator.mediaDevices.getUserMedia({ // <1> | |
video: false, | |
audio: true, | |
}) | |
if (!MediaRecorder.isTypeSupported('audio/webm')) { // <2> | |
console.warn('audio/webm is not supported') | |
} | |
const mediaRecorder = new MediaRecorder(stream, { // <3> | |
mimeType: 'audio/webm', | |
}) | |
buttonStart.addEventListener('click', () => { | |
mediaRecorder.start() // <4> | |
buttonStart.setAttribute('disabled', '') | |
buttonStop.removeAttribute('disabled') | |
}) | |
buttonStop.addEventListener('click', () => { | |
mediaRecorder.stop() // <5> | |
buttonStart.removeAttribute('disabled') | |
buttonStop.setAttribute('disabled', '') | |
}) | |
mediaRecorder.addEventListener('dataavailable', event => { // <6> | |
player.src = URL.createObjectURL(event.data) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment