当前位置:   article > 正文

一个可以直接运行的WEB录音机,在WEB上实现录音并播放,也可以用来测试麦克风(增加了音频下载功能)_网页录音机

网页录音机

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta name="apple-mobile-web-capable" content="yes">
    <title>WEB录音机</title>
 
</head>
 
<body>
    <button onclick="record()">开始录音</button>
    <button onclick="stopRecord()">停止录音</button>
    <button onclick="bofangRecord()">播放录音</button>
    <button onclick="recordClose()">关闭录音</button>
    <audio class="audio-node" autoplay></audio>
</body>
<script type="text/javascript">
    function record() {
        window.navigator.mediaDevices.getUserMedia({
            audio: {
                sampleRate: 44100, // 采样率
                channelCount: 2,   // 声道
                volume: 2.0        // 音量
            }
        }).then(mediaStream => {
            console.log(mediaStream);
            window.mediaStream = mediaStream
            beginRecord(window.mediaStream);
        }).catch(err => {
            // 如果用户电脑没有麦克风设备或者用户拒绝了,或者连接出问题了等
            // 这里都会抛异常,并且通过err.name可以知道是哪种类型的错误 
            console.error(err);
        });
    }
    function beginRecord(mediaStream) {
        let audioContext = new (window.AudioContext || window.webkitAudioContext);
        let mediaNode = audioContext.createMediaStreamSource(mediaStream);
        console.log(mediaNode)
        window.mediaNode = mediaNode
        // 这里connect之后就会自动播放了
        // mediaNode.connect(audioContext.destination);	//直接把录的音直接播放出来
        // 创建一个jsNode
        let jsNode = createJSNode(audioContext);
        window.jsNode = jsNode
        // 需要连到扬声器消费掉outputBuffer,process回调才能触发
        // 并且由于不给outputBuffer设置内容,所以扬声器不会播放出声音
        jsNode.connect(audioContext.destination);
        jsNode.onaudioprocess = onAudioProcess;
        // 把mediaNode连接到jsNode
        mediaNode.connect(jsNode);
    }
    function createJSNode(audioContext) {
        const BUFFER_SIZE = 4096;	//4096
        const INPUT_CHANNEL_COUNT = 2;
        const OUTPUT_CHANNEL_COUNT = 2;
        // createJavaScriptNode已被废弃
        let creator = audioContext.createScriptProcessor || audioContext.createJavaScriptNode;
        creator = creator.bind(audioContext);
        return creator(BUFFER_SIZE,
            INPUT_CHANNEL_COUNT, OUTPUT_CHANNEL_COUNT);
    }
    let leftDataList = [],
        rightDataList = [];
    function onAudioProcess(event) {
        // console.log(event.inputBuffer);
        let audioBuffer = event.inputBuffer;
        let leftChannelData = audioBuffer.getChannelData(0),
            rightChannelData = audioBuffer.getChannelData(1);
        // console.log(leftChannelData, rightChannelData);
        // 需要克隆一下
        leftDataList.push(leftChannelData.slice(0));
        rightDataList.push(rightChannelData.slice(0));
    }
    function bofangRecord() {
        // 播放录音
        let leftData = mergeArray(leftDataList),
            rightData = mergeArray(rightDataList);
        if (leftData == null || leftData == null) {
            alert("请先录音再播放");
            return;
        }
        let allData = interleaveLeftAndRight(leftData, rightData);
        let wavBuffer = createWavFile(allData);
        playRecord(wavBuffer);
    }
    function playRecord(arrayBuffer) {
        let blob = new Blob([new Uint8Array(arrayBuffer)]);
        let blobUrl = URL.createObjectURL(blob);
        document.querySelector('.audio-node').src = blobUrl;
		// 增加了下载功能
  		const aLink = document.createElement('a')   
        aLink.href = blobUrl
        // 文件名字
        aLink.download = '测试数据.mp3'
        document.body.appendChild(aLink)
        aLink.click()
        aLink.remove();
    }
    function stopRecord() {
        // 停止录音
        window.mediaNode.disconnect();
        window.jsNode.disconnect();
        console.log("已停止录音")
        // console.log(leftDataList, rightDataList);
    }
    function recordClose() {
        if (window.mediaStream == null || window.mediaStream.getAudioTracks() == null || window.mediaStream.getAudioTracks().length == 0) {
            return;
        }
        // 停止语音
        window.mediaStream.getAudioTracks()[0].stop();
        console.log("已停止语音")
    }
    function mergeArray(list) {
        if (list == null || list.length == 0 || list[0] == null || list[0].length == 0) {
            return null;
        }
        let length = list.length * list[0].length;
        let data = new Float32Array(length),
            offset = 0;
        for (let i = 0; i < list.length; i++) {
            data.set(list[i], offset);
            offset += list[i].length;
        }
        return data;
    }
    function interleaveLeftAndRight(left, right) {
        // 交叉合并左右声道的数据
        let totalLength = left.length + right.length;
        let data = new Float32Array(totalLength);
        for (let i = 0; i < left.length; i++) {
            let k = i * 2;
            data[k] = left[i];
            data[k + 1] = right[i];
        }
        return data;
    }
    function createWavFile(audioData) {
        const WAV_HEAD_SIZE = 44;
        let buffer = new ArrayBuffer(audioData.length * 2 + WAV_HEAD_SIZE),
            // 需要用一个view来操控buffer
            view = new DataView(buffer);
        // 写入wav头部信息
        // RIFF chunk descriptor/identifier
        writeUTFBytes(view, 0, 'RIFF');
        // RIFF chunk length
        view.setUint32(4, 44 + audioData.length * 2, true);
        // RIFF type
        writeUTFBytes(view, 8, 'WAVE');
        // format chunk identifier
        // FMT sub-chunk
        writeUTFBytes(view, 12, 'fmt ');
        // format chunk length
        view.setUint32(16, 16, true);
        // sample format (raw)
        view.setUint16(20, 1, true);
        // stereo (2 channels)
        view.setUint16(22, 2, true);
        // sample rate
        view.setUint32(24, 44100, true);
        // byte rate (sample rate * block align)
        view.setUint32(28, 44100 * 2, true);
        // block align (channel count * bytes per sample)
        view.setUint16(32, 2 * 2, true);
        // bits per sample
        view.setUint16(34, 16, true);
        // data sub-chunk
        // data chunk identifier
        writeUTFBytes(view, 36, 'data');
        // data chunk length
        view.setUint32(40, audioData.length * 2, true);
        // 写入wav头部,代码同上
        // 写入PCM数据
        let length = audioData.length;
        let index = 44;
        let volume = 1;
        for (let i = 0; i < length; i++) {
            view.setInt16(index, audioData[i] * (0x7FFF * volume), true);
            index += 2;
        }
        return buffer;
    }
    function writeUTFBytes(view, offset, string) {
        var lng = string.length;
        for (var i = 0; i < lng; i++) {
            view.setUint8(offset + i, string.charCodeAt(i));
        }
    }
 
</script>
 
</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
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196

原文链接:https://blog.csdn.net/xxxmatata/article/details/124213131

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/571473
推荐阅读
相关标签
  

闽ICP备14008679号