Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Last active September 5, 2023 12:22
Show Gist options
  • Save tatsuyasusukida/ec7f682629171b420726099451992c02 to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/ec7f682629171b420726099451992c02 to your computer and use it in GitHub Desktop.
🎤 How to record audio using the MediaStream Recording API in JavaScript

🎤 How to record audio using the MediaStream Recording API in JavaScript

<!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>
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