Skip to content

Instantly share code, notes, and snippets.

@dcsuibian
Created February 13, 2022 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcsuibian/324d402d39046f5d9d5095c2937121e6 to your computer and use it in GitHub Desktop.
Save dcsuibian/324d402d39046f5d9d5095c2937121e6 to your computer and use it in GitHub Desktop.
回声
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: skyblue;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
main h2:nth-child(2) {
display: none;
}
main.recording h2:first-child {
display: none;
}
main.recording h2:nth-child(2) {
display: block;
}
</style>
<title>回声</title>
</head>
<body>
<main>
<h2>按下空格开始录音</h2>
<h2>Recording...</h2>
<audio></audio>
</main>
<script>
'use strict';
const audio = document.querySelector('audio');
const main = document.querySelector('main');
async function bootstrap() {
// 请求录音权限,只有通过了才能继续
const stream = await navigator.mediaDevices.getUserMedia({audio: true});
const recorder = new MediaRecorder(stream)
let audioChunks = [];// 存储录音的数据
recorder.addEventListener('dataavailable', e => {
audioChunks.push(e.data);
});
recorder.addEventListener('stop', () => {
console.debug('recorder stopped');
const audioBlob = new Blob(audioChunks, {type: 'audio/mp3'});
const audioUrl = URL.createObjectURL(audioBlob);
audio.src = audioUrl;
audio.play().catch(e => void 0);
});
recorder.addEventListener('start', () => {
console.debug('recorder started');
// 情况audioChunks,避免之前的数据影响
audioChunks = [];
});
/*
* 延迟一点点时间启动录音是为了避免录到按键声
* recorder.state === 'recording' 可以判断是否正在录音
* keydown事件会在按住时反复触发,null !== timer 主要是为了避免在这一小段时间内多次处理
*/
let timer = null
document.addEventListener('keydown', e => {
if (e.key !== ' ' || recorder.state === 'recording' || null !== timer) return;
// 停止播放音频,针对上次的音频还没放完,就重新开始录音的情况
audio.pause()
URL.revokeObjectURL(audio.src)
main.classList.add('recording');
// 开始录音
timer = setTimeout(() => {
if (null === timer) return;
recorder.start();
timer = null;
}, 150);
})
document.addEventListener('keyup', e => {
if (e.key !== ' ') return;
main.classList.remove('recording');
if (null !== timer) {
timer = null
} else {
recorder.stop()
}
})
}
bootstrap().catch(err => {
alert('获取录音权限失败');
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment