全国服务热线:4008-888-888

技术知识

HTML5响声录制/播发作用的完成编码

html编码:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf⑻" />
        <title>火花黑洞</title>
    </head>
    <body>
        <div>
            <audio autoplay></audio>
            <input onclick="startRecording()" type="button" value="音频" />
            <input onclick="stopRecording()" type="button" value="终止" />
            <input onclick="playRecording()" type="button" value="播发" />
            <input onclick="uploadAudio()" type="button" value="递交" />
            <br />
            <div id="recordingslist"></div>
        </div>
        <script type="text/javascript" src="js/HZRecorder.js"></script>
        <script>
            var recorder;
            var audio = document.querySelector('audio');
            function startRecording() {
                HZRecorder.get(function(rec) {
                    recorder = rec;
                    recorder.start();
                }, {
                    sampleBits: 16,
                    sampleRate: 16000
                });
            }
            function stopRecording() {
                recorder.stop();
                var blob = recorder.getBlob();
                var url = URL.createObjectURL(blob);
                var div = document.createElement('div');
                var au = document.createElement('audio');
                var hf = document.createElement('a');
                au.controls = true;
                au.src = url;
                hf.href = url;
                hf.download = new Date().toISOString() + '.wav';
                hf.innerHTML = hf.download;
                div.appendChild(au);
                div.appendChild(hf);
                recordingslist.appendChild(div);
            }
            function playRecording() {
                recorder.play(audio);
            }
            function uploadAudio() {
                recorder.upload("Handler1.ashx", function(state, e) {
                    switch(state) {
                        case 'uploading':
                            //var percentComplete = Math.round(e.loaded * 100 / e.total) + '%';
                            break;
                        case 'ok':
                            //alert(e.target.responseText);
                            alert("提交取得成功");
                            break;
                        case 'error':
                            alert("提交不成功");
                            break;
                        case 'cancel':
                            alert("提交被撤销");
                            break;
                    }
                });
            }
        </script>
    </body>
</html>

HZRecorder.js

(function (window) {
    //适配
    window.URL = window.URL || window.webkitURL;
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    var HZRecorder = function (stream, config) {
        config = config || {};
        config.sampleBits = config.sampleBits || 8      //取样多位 8, 16
        config.sampleRate = config.sampleRate || (44100 / 6);   //取样率(1/6 44100)
        var context = new (window.webkitAudioContext || window.AudioContext)();
        var audioInput = context.createMediaStreamSource(stream);
        var createScript = context.createScriptProcessor || context.createJavaScriptNode;
        var recorder = createScript.apply(context, [4096, 1, 1]);
        var mp3ReceiveSuccess, currentErrorCallback;
        var audioData = {
            size: 0          //音频文档长度
            , buffer: []     //音频缓存文件
            , inputSampleRate: context.sampleRate    //键入取样率
            , inputSampleBits: 16       //键入取样多位 8, 16
            , outputSampleRate: config.sampleRate    //輸出取样率
            , oututSampleBits: config.sampleBits       //輸出取样多位 8, 16
            , input: function (data) {
                this.buffer.push(new Float32Array(data));
                this.size += data.length;
            }
            , compress: function () { //合拼缩小
                //合拼
                var data = new Float32Array(this.size);
                var offset = 0;
                for (var i = 0; i < this.buffer.length; i++) {
                    data.set(this.buffer[i], offset);
                    offset += this.buffer[i].length;
                }
                //缩小
                var compression = parseInt(this.inputSampleRate / this.outputSampleRate);
                var length = data.length / compression;
                var result = new Float32Array(length);
                var index = 0, j = 0;
                while (index < length) {
                    result[index] = data[j];
                    j += compression;
                    index++;
                }
                return result;
            }
            , encodeWAV: function () {
                var sampleRate = Math.min(this.inputSampleRate, this.outputSampleRate);
                var sampleBits = Math.min(this.inputSampleBits, this.oututSampleBits);
                var bytes = this.compress();
                var dataLength = bytes.length * (sampleBits / 8);
                var buffer = new ArrayBuffer(44 + dataLength);
                var data = new DataView(buffer);
                var channelCount = 1;//单声道
                var offset = 0;
                var writeString = function (str) {
                    for (var i = 0; i < str.length; i++) {
                        data.setUint8(offset + i, str.charCodeAt(i));
                    }
                }
                // 資源互换文档标志符 
                writeString('RIFF'); offset += 4;
                // 下个详细地址刚开始到文档尾总字节数,即文档尺寸⑻ 
                data.setUint32(offset, 36 + dataLength, true); offset += 4;
                // WAV文档标示
                writeString('WAVE'); offset += 4;
                // 波形文件格式标示 
                writeString('fmt '); offset += 4;
                // 过虑字节,1般为 0x10 = 16 
                data.setUint32(offset, 16, true); offset += 4;
                // 文件格式种别 (PCM方式取样数据信息) 
                data.setUint16(offset, 1, true); offset += 2;
                // 安全通道数 
                data.setUint16(offset, channelCount, true); offset += 2;
                // 取样率,每秒样版数,表明每一个安全通道的播发速率 
                data.setUint32(offset, sampleRate, true); offset += 4;
                // 波形数据信息传送率 (每秒均值字节数) 单声道×每秒数据信息位数×每样版数据信息位/8 
                data.setUint32(offset, channelCount * sampleRate * (sampleBits / 8), true); offset += 4;
                // 快数据信息调剂数 取样1次占有字节数 单声道×每样版的数据信息位数/8 
                data.setUint16(offset, channelCount * (sampleBits / 8), true); offset += 2;
                // 每样版数据信息位数 
                data.setUint16(offset, sampleBits, true); offset += 2;
                // 数据信息标志符 
                writeString('data'); offset += 4;
                // 取样数据信息总数,即数据信息总尺寸⑷4 
                data.setUint32(offset, dataLength, true); offset += 4;
                // 写入取样数据信息 
                if (sampleBits === 8) {
                    for (var i = 0; i < bytes.length; i++, offset++) {
                        var s = Math.max(⑴, Math.min(1, bytes[i]));
                        var val = s < 0 ? s * 0x8000 : s * 0x7FFF;
                        val = parseInt(255 / (65535 / (val + 32768)));
                        data.setInt8(offset, val, true);
                    }
                } else {
                    for (var i = 0; i < bytes.length; i++, offset += 2) {
                        var s = Math.max(⑴, Math.min(1, bytes[i]));
                        data.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
                    }
                }
                return new Blob([data], { type: 'audio/wav' });
            }
        };
        //刚开始音频
        this.start = function () {
            audioInput.connect(recorder);
            recorder.connect(context.destination);
        }
        //终止
        this.stop = function () {
            recorder.disconnect();
        }
        //获得声频文档
        this.getBlob = function () {
            this.stop();
            return audioData.encodeWAV();
        }
        //回放
        this.play = function (audio) {
            audio.src = window.URL.createObjectURL(this.getBlob());
        }
        //提交
        this.upload = function (url, callback) {
            var fd = new FormData();
            fd.append("audioData", this.getBlob());
            var xhr = new XMLHttpRequest();
            if (callback) {
                xhr.upload.addEventListener("progress", function (e) {
                    callback('uploading', e);
                }, false);
                xhr.addEventListener("load", function (e) {
                    callback('ok', e);
                }, false);
                xhr.addEventListener("error", function (e) {
                    callback('error', e);
                }, false);
                xhr.addEventListener("abort", function (e) {
                    callback('cancel', e);
                }, false);
            }
            xhr.open("POST", url);
            xhr.send(fd);
        }
        //声频收集
        recorder.onaudioprocess = function (e) {
            audioData.input(e.inputBuffer.getChannelData(0));
            //record(e.inputBuffer.getChannelData(0));
        }
    };
    //抛出出现异常
    HZRecorder.throwError = function (message) {
        alert(message);
        throw new function () { this.toString = function () { return message; } }
    }
    //是不是适用音频
    HZRecorder.canRecording = (navigator.getUserMedia != null);
    //获得音频机
    HZRecorder.get = function (callback, config) {
        if (callback) {
            if (navigator.getUserMedia) {
                navigator.getUserMedia(
                    { audio: true } //只开启声频
                    , function (stream) {
                        var rec = new HZRecorder(stream, config);
                        callback(rec);
                    }
                    , function (error) {
                        switch (error.code || error.name) {
                            case 'PERMISSION_DENIED':
                            case 'PermissionDeniedError':
                                HZRecorder.throwError('客户回绝出示信息内容。');
                                break;
                            case 'NOT_SUPPORTED_ERROR':
                            case 'NotSupportedError':
                                HZRecorder.throwError('访问器不适用硬件配置机器设备。');
                                break;
                            case 'MANDATORY_UNSATISFIED_ERROR':
                            case 'MandatoryUnsatisfiedError':
                                HZRecorder.throwError('没法发现特定的硬件配置机器设备。');
                                break;
                            default:
                                HZRecorder.throwError('没法开启话筒。出现异常信息内容:' + (error.code || error.name));
                                break;
                        }
                    });
            } else {
                HZRecorder.throwErr('当今访问器不适用音频作用。'); return;
            }
        }
    }
    window.HZRecorder = HZRecorder;
})(window);

总结

以上所述是网编给大伙儿详细介绍的HTML5响声录制/播发作用的完成编码,期待对大伙儿有一定的协助,假如大伙儿有任何疑惑请给我留言,网编会立即回应大伙儿的。在此也十分谢谢大伙儿对脚本制作之家网站的适用!



在线客服

关闭

客户服务热线
4008-888-888


点击这里给我发消息 在线客服

点击这里给我发消息 在线客服