# 麦克风

主要使用:

  • navigator.mediaDevices.getUserMedia
  • AudioContext
  • createMediaStreamSource
  • createScriptProcessor

# 效果


# 代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>麦克风</title>

  <style>
    #box {
      height: 100px;
      display: flex;
      align-items: center;
      background-color: #efefef;
    }
    #box>span {
      /* flex: 1; */
      width: 10px;
      min-height: 1px;
      border-radius: 2px;
      background-color: #000000;
    }
  </style>

</head>
<!-- https://dev.eztest.org/monitor/session/3458/#/ -->
<body>
  <h2>麦克风 声波曲线</h2>
  <button onclick="detectDevice()">授权 & 采集</button>
  <button onclick="closeMicro()">关闭</button>
  <br>
  <br>
  <!-- <canvas id="oscilloscope" style="width: 600px; height: 200px;"></canvas> -->
  <div id="box"></div>

  <script>
    let logIng = false;
    const box = document.getElementById('box');
    // let audioContext = new (window.AudioContext || window.webkitAudioContext)();
    let audioContext = null;
    let mediaStreamSource = null;
    let scriptProcessor = null;
    // console.log(audioContext);
    function detectDevice() {
      audioContext = new AudioContext();
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        // 获取用户的 media 信息
        navigator.mediaDevices.getUserMedia({ audio: true })
          .then((stream) => {
            console.log(stream);
            // 将麦克风的声音输入这个对象
            mediaStreamSource = audioContext.createMediaStreamSource(stream);
            // 创建一个音频分析对象,采样的缓冲区大小为4096,输入和输出都是单声道
            scriptProcessor = audioContext.createScriptProcessor(2048,1,1); // 0, 256, 512, 1024, 2048, 4069, 8192, 16384
            // 将该分析对象与麦克风音频进行连接
            mediaStreamSource.connect(scriptProcessor);
            // 此举无甚效果,仅仅是因为解决 Chrome 自身的 bug
            scriptProcessor.connect(audioContext.destination);

            console.log(scriptProcessor);
            logIng = true;
            // 开始处理音频
            scriptProcessor.onaudioprocess = function(e) {
              // 获得缓冲区的输入音频,转换为包含了PCM通道数据的32位浮点数组
              let buffer = e.inputBuffer.getChannelData(0);
              // 获取缓冲区中最大的音量值
              let maxVal = Math.max.apply(Math, buffer);
              // console.log(e, buffer, maxVal);
              const height = Math.round(maxVal*100);
              // console.log(logIng, height);
              if(logIng) {
                const span = document.createElement('span');
                // console.log(height);
                span.style.height = `${height}px`;
                box.appendChild(span)
              }
            };
          })
          .catch((err) => {
            const tip = '麦克风授权失败!';
            alert(tip);
            throw Error(tip);
          });
      } else {
        alert('麦克风已禁用,或浏览器不支持此功能,请到浏览器设置中查看。');
        throw Error('浏览器不支持此功能!');
      }
    }

    function closeMicro() {
      // console.log('close =>>>>');
      if(audioContext!== null) {
        audioContext.close()
        .then(() => {
          console.log('close =>>>>');
          logIng = false;
          mediaStreamSource.disconnect();
          scriptProcessor.disconnect();
          audioContext = null;
        });
      }
    }
  </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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
上次更新: 2022-11-29 16:59:20(UTC +8)