HTML5声音录制/播放功能的实现代码
程序员文章站
2023-11-12 09:49:16
本文通过实例代码给大家介绍了HTML5声音录制/播放功能,非常不错,具有参考借鉴价值,需要的朋友跟随脚本之家小编一起学习吧... 18-05-03...
html代码:
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <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; // 下个地址开始到文件尾总字节数,即文件大小-8 data.setuint32(offset, 36 + datalength, true); offset += 4; // wav文件标志 writestring('wave'); offset += 4; // 波形格式标志 writestring('fmt '); offset += 4; // 过滤字节,一般为 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; // 快数据调整数 采样一次占用字节数 单声道×每样本的数据位数/8 data.setuint16(offset, channelcount * (samplebits / 8), true); offset += 2; // 每样本数据位数 data.setuint16(offset, samplebits, true); offset += 2; // 数据标识符 writestring('data'); offset += 4; // 采样数据总数,即数据总大小-44 data.setuint32(offset, datalength, true); offset += 4; // 写入采样数据 if (samplebits === 8) { for (var i = 0; i < bytes.length; i++, offset++) { var s = math.max(-1, 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(-1, 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声音录制/播放功能的实现代码,希望对大家有所帮助