webrtc初探
呛再首 6/21/2020 技巧
# WebRtc 源码目录结构
# 唤起录音
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<audio id="recordedAudio" src=""></audio>
<body>
<script>
async function startRecording () {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
const mediaRecorder = new MediaRecorder(stream)
const chunks = []
mediaRecorder.addEventListener("dataavailable", (event) => {
chunks.push(event.data)
})
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(chunks, { type: "audio/wav" })
const audioUrl = URL.createObjectURL(audioBlob)
// 获取 audio 标签,并设置 src 属性
const audioElement = document.getElementById("recordedAudio")
audioElement.src = audioUrl
// 播放录音
audioElement.play()
})
mediaRecorder.start()
console.log("开始录音")
setTimeout(() => {
mediaRecorder.stop()
console.log("结束录音")
}, 5000) // 录音时长为 5 秒
} catch (err) {
console.error("无法访问麦克风:" + err)
}
}
startRecording()
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51