@da-web/js-audio-recorder
Version:
js audio recorder plugin
12 lines • 16.7 kB
JavaScript
/*!
*
* js-audio-recorder - js audio recorder plugin
*
* @version v1.2.1
* @homepage https://github.com/2fps/recorder
* @author 2fps <echoweb@126.com> (https://www.zhuyuntao.cn)
* @license MIT
*
*/
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Recorder=e():t.Recorder=e()}(this,function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=1)}([function(t,e,n){"use strict";function r(t,e,n){for(var r=0;r<n.length;r++)t.setUint8(e+r,n.charCodeAt(r))}Object.defineProperty(e,"__esModule",{value:!0}),e.compress=function(t,e,n){for(var r=e/n,i=Math.max(r,1),o=t.left,a=t.right,s=Math.floor((o.length+a.length)/r),u=new Float32Array(s),l=0,c=0;l<s;){var f=Math.floor(c);u[l]=o[f],l++,a.length&&(u[l]=a[f],l++),c+=i}return u},e.encodePCM=function(t,e,n){void 0===n&&(n=!0);var r=0,i=t.length*(e/8),o=new ArrayBuffer(i),a=new DataView(o);if(8===e)for(var s=0;s<t.length;s++,r++){var u=(l=Math.max(-1,Math.min(1,t[s])))<0?128*l:127*l;u=+u+128,a.setInt8(r,u)}else for(s=0;s<t.length;s++,r+=2){var l=Math.max(-1,Math.min(1,t[s]));a.setInt16(r,l<0?32768*l:32767*l,n)}return a},e.encodeWAV=function(t,e,n,i,o,a){void 0===a&&(a=!0);var s=n>e?e:n,u=o,l=new ArrayBuffer(44+t.byteLength),c=new DataView(l),f=i,p=0;r(c,p,"RIFF"),p+=4,c.setUint32(p,36+t.byteLength,a),r(c,p+=4,"WAVE"),r(c,p+=4,"fmt "),p+=4,c.setUint32(p,16,a),p+=4,c.setUint16(p,1,a),p+=2,c.setUint16(p,f,a),p+=2,c.setUint32(p,s,a),p+=4,c.setUint32(p,f*s*(u/8),a),p+=4,c.setUint16(p,f*(u/8),a),p+=2,c.setUint16(p,u,a),r(c,p+=2,"data"),p+=4,c.setUint32(p,t.byteLength,a),p+=4;for(var d=0;d<t.byteLength;)c.setUint8(p,t.getUint8(d)),p++,d++;return c}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(2),a=n(0),s=n(3),u=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this;return n.isrecording=!1,n.ispause=!1,n.isplaying=!1,n}return i(e,t),e.prototype.setOption=function(t){void 0===t&&(t={}),this.setNewOption(t)},e.prototype.start=function(){return this.isrecording?Promise.reject():(this.isrecording=!0,this.startRecord())},e.prototype.pause=function(){this.isrecording&&!this.ispause&&(this.ispause=!0,this.pauseRecord())},e.prototype.resume=function(){this.isrecording&&this.ispause&&(this.ispause=!1,this.resumeRecord())},e.prototype.stop=function(){this.isrecording&&(this.isrecording=!1,this.ispause=!1,this.stopRecord())},e.prototype.play=function(){this.stop(),this.isplaying=!0,this.onplay&&this.onplay(),s.default.addPlayEnd(this.onplayend);var t=this.getWAV();t.byteLength>44&&s.default.play(t.buffer)},e.prototype.getPlayTime=function(){return s.default.getPlayTime()},e.prototype.pausePlay=function(){!this.isrecording&&this.isplaying&&(this.isplaying=!1,this.onpauseplay&&this.onpauseplay(),s.default.pausePlay())},e.prototype.resumePlay=function(){this.isrecording||this.isplaying||(this.isplaying=!0,this.onresumeplay&&this.onresumeplay(),s.default.resumePlay())},e.prototype.stopPlay=function(){this.isrecording||(this.isplaying=!1,this.onstopplay&&this.onstopplay(),s.default.stopPlay())},e.prototype.destroy=function(){return s.default.destroyPlay(),this.destroyRecord()},e.prototype.getRecordAnalyseData=function(){return this.getAnalyseData()},e.prototype.getPlayAnalyseData=function(){return s.default.getAnalyseData()},e.prototype.getPCM=function(){this.stop();var t=this.getData();return t=a.compress(t,this.inputSampleRate,this.outputSampleRate),a.encodePCM(t,this.oututSampleBits,this.littleEdian)},e.prototype.getPCMBlob=function(){return new Blob([this.getPCM()])},e.prototype.downloadPCM=function(t){void 0===t&&(t="recorder");var e=this.getPCMBlob();o.downloadPCM(e,t)},e.prototype.getWAV=function(){var t=this.getPCM();return a.encodeWAV(t,this.inputSampleRate,this.outputSampleRate,this.config.numChannels,this.oututSampleBits,this.littleEdian)},e.prototype.getWAVBlob=function(){return new Blob([this.getWAV()],{type:"audio/wav"})},e.prototype.downloadWAV=function(t){void 0===t&&(t="recorder");var e=this.getWAVBlob();o.downloadWAV(e,t)},e.prototype.download=function(t,e,n){o.download(t,e,n)},e.prototype.getChannelData=function(){var t=this.getPCM(),e=t.byteLength,n=this.littleEdian,r={left:null,right:null};if(2===this.config.numChannels){var i=new DataView(new ArrayBuffer(e/2)),o=new DataView(new ArrayBuffer(e/2));if(16===this.config.sampleBits)for(var a=0;a<e/2;a+=2)i.setInt16(a,t.getInt16(2*a,n),n),o.setInt16(a,t.getInt16(2*a+2,n),n);else for(a=0;a<e/2;a+=2)i.setInt8(a,t.getInt8(2*a)),o.setInt8(a,t.getInt8(2*a+1));r.left=i,r.right=o}else r.left=t;return r},e}(n(5).default);e.default=u},function(t,e,n){"use strict";function r(t,e,n){var r=document.createElement("a");r.href=window.URL.createObjectURL(t),r.download=e+"."+n,r.click()}Object.defineProperty(e,"__esModule",{value:!0}),e.downloadWAV=function(t,e){void 0===e&&(e="recorder"),r(t,e,"wav")},e.downloadPCM=function(t,e){void 0===e&&(e="recorder"),r(t,e,"pcm")},e.download=function(t,e,n){return r(t,e,n)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(4),i=null,o=0,a=0,s=null,u=null,l=null,c=!1,f=0,p=function(){};function d(){return c=!1,s.decodeAudioData(l.slice(0),function(t){(i=s.createBufferSource()).onended=function(){c||(f=s.currentTime-a+o,p())},i.buffer=t,i.connect(u),u.connect(s.destination),i.start(0,o),a=s.currentTime},function(t){r.throwError(t)})}function h(){i&&(i.stop(),i=null)}var y=function(){function t(){}return t.play=function(t){return s||(s=new(window.AudioContext||window.webkitAudioContext),(u=s.createAnalyser()).fftSize=2048),this.stopPlay(),l=t,f=0,d()},t.pausePlay=function(){h(),o+=s.currentTime-a,c=!0},t.resumePlay=function(){return d()},t.stopPlay=function(){o=0,l=null,h()},t.destroyPlay=function(){this.stopPlay()},t.getAnalyseData=function(){var t=new Uint8Array(u.frequencyBinCount);return u.getByteTimeDomainData(t),t},t.addPlayEnd=function(t){void 0===t&&(t=function(){}),p=t},t.getPlayTime=function(){var t=c?o:s.currentTime-a+o;return f||t},t}();e.default=y},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.throwError=function(t){throw new Error(t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(6),i=n(0),o=n(7),a=function(){function t(e){void 0===e&&(e={}),this.size=0,this.lBuffer=[],this.rBuffer=[],this.tempPCM=[],this.inputSampleBits=16,this.fileSize=0,this.duration=0,this.speaking=!1,this.needRecord=!0;var n,r=new(window.AudioContext||window.webkitAudioContext);this.inputSampleRate=r.sampleRate,this.setNewOption(e),this.littleEdian=(n=new ArrayBuffer(2),new DataView(n).setInt16(0,256,!0),256===new Int16Array(n)[0]),t.initUserMedia()}return t.prototype.setNewOption=function(t){void 0===t&&(t={}),this.config={sampleBits:~[8,16].indexOf(t.sampleBits)?t.sampleBits:16,sampleRate:~[8e3,11025,16e3,22050,24e3,44100,48e3].indexOf(t.sampleRate)?t.sampleRate:this.inputSampleRate,numChannels:~[1,2].indexOf(t.numChannels)?t.numChannels:1,volumeThreshold:t.volumeThreshold},this.outputSampleRate=this.config.sampleRate,this.oututSampleBits=this.config.sampleBits,this.silenceDurationNotify=t.silenceDurationNotify||-1},t.prototype.startRecord=function(){var t=this;return this.context&&this.destroyRecord(),this.initRecorder(),navigator.mediaDevices.getUserMedia({audio:!0}).then(function(e){t.audioInput=t.context.createMediaStreamSource(e),t.stream=e}).then(function(){t.audioInput.connect(t.analyser),t.analyser.connect(t.recorder),t.recorder.connect(t.context.destination)})},t.prototype.pauseRecord=function(){this.needRecord=!1},t.prototype.resumeRecord=function(){this.needRecord=!0},t.prototype.stopRecord=function(){this.audioInput&&this.audioInput.disconnect(),this.source&&this.source.stop(),this.recorder.disconnect(),this.analyser.disconnect(),this.needRecord=!0},t.prototype.destroyRecord=function(){return this.clearRecordStatus(),this.stopStream(),this.closeAudioContext()},t.prototype.getAnalyseData=function(){var t=new Uint8Array(this.analyser.frequencyBinCount);return this.analyser.getByteTimeDomainData(t),t},t.prototype.getData=function(){return this.flat()},t.prototype.clearRecordStatus=function(){this.lBuffer.length=0,this.rBuffer.length=0,this.size=0,this.fileSize=0,this.PCM=null,this.audioInput=null,this.duration=0},t.prototype.flat=function(){var t=null,e=new Float32Array(0);1===this.config.numChannels?t=new Float32Array(this.size):(t=new Float32Array(this.size/2),e=new Float32Array(this.size/2));for(var n=0,r=0;r<this.lBuffer.length;r++)t.set(this.lBuffer[r],n),n+=this.lBuffer[r].length;n=0;for(r=0;r<this.rBuffer.length;r++)e.set(this.rBuffer[r],n),n+=this.rBuffer[r].length;return{left:t,right:e}},t.prototype.initRecorder=function(){var t=this;this.clearRecordStatus(),this.context=new(window.AudioContext||window.webkitAudioContext),this.analyser=this.context.createAnalyser(),this.analyser.fftSize=2048;var e=this.context.createScriptProcessor||this.context.createJavaScriptNode;this.recorder=e.apply(this.context,[4096,this.config.numChannels,this.config.numChannels]),this.lastProcessAudioDuration=0,this.recorder.onaudioprocess=function(e){if(t.needRecord){var n,i=e.inputBuffer.getChannelData(0),a=null;if((n=100*Math.max.apply(Math,i))<(t.config.volumeThreshold||8)){if(console.debug("声音太小,不录"),t.speaking)t.speaking=!1,t.lastNoSpeakTime=Date.now();else if(-1!=t.silenceDurationNotify&&Date.now()-t.lastNoSpeakTime>t.silenceDurationNotify){if(t.silenceHasNotify)return;t.silenceHasNotify=!0,t.onsilence&&t.onsilence()}t.onprogress&&t.onprogress({duration:t.duration,fileSize:t.fileSize,vol:n,speaking:t.speaking})}else{if(t.speaking=!0,t.lBuffer.push(new Float32Array(i)),t.size+=i.length,2===t.config.numChannels&&(a=e.inputBuffer.getChannelData(1),t.rBuffer.push(new Float32Array(a)),t.size+=a.length),t.duration+=4096/t.inputSampleRate,t.duration-t.lastProcessAudioDuration>=2){t.lastProcessAudioDuration=t.duration;var s=o.createAssistWorker().onMessage(function(e){s.terminate(),t.onwav&&t.onwav(e)}).create(r.encoderToPcmJob);s.run({lBuffer:t.lBuffer,rBuffer:t.rBuffer,numChannels:t.config.numChannels,size:t.size,inputSampleRate:t.inputSampleRate,outputSampleRate:t.outputSampleRate,oututSampleBits:t.oututSampleBits,littleEdian:t.littleEdian})}t.fileSize=Math.floor(t.size/Math.max(t.inputSampleRate/t.outputSampleRate,1))*(t.oututSampleBits/8),t.onprocess&&t.onprocess(t.duration),t.onprogress&&t.onprogress({duration:t.duration,fileSize:t.fileSize,vol:n,speaking:t.speaking})}}}},t.prototype.stopStream=function(){this.stream&&this.stream.getTracks&&(this.stream.getTracks().forEach(function(t){return t.stop()}),this.stream=null)},t.prototype.closeAudioContext=function(){return this.context&&this.context.close&&"closed"!==this.context.state?this.context.close():new Promise(function(t){t()})},t.initUserMedia=function(){void 0===navigator.mediaDevices&&(navigator.mediaDevices={}),void 0===navigator.mediaDevices.getUserMedia&&(navigator.mediaDevices.getUserMedia=function(t){var e=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia;return e?new Promise(function(n,r){e.call(navigator,t,n,r)}):Promise.reject(new Error("浏览器不支持 getUserMedia !"))})},t.prototype.transformIntoPCM=function(t,e){var n=new Float32Array(t),r=new Float32Array(e),o=i.compress({left:n,right:r},this.inputSampleRate,this.outputSampleRate);return i.encodePCM(o,this.oututSampleBits,this.littleEdian)},t.getPermission=function(){return this.initUserMedia(),navigator.mediaDevices.getUserMedia({audio:!0}).then(function(t){t&&t.getTracks().forEach(function(t){return t.stop()})})},t}();e.default=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.encoderToPcmJob=function(t,e){var n=t.lBuffer,r=t.rBuffer,i=t.numChannels,o=t.size,a=t.inputSampleRate,s=t.outputSampleRate,u=t.oututSampleBits,l=t.littleEdian,c=e.postMessage;function f(t,e,n){for(var r=0;r<n.length;r++)t.setUint8(e+r,n.charCodeAt(r))}var p=function(t,e,n,r){var i=null,o=new Float32Array(0);1===r?i=new Float32Array(n):(i=new Float32Array(n/2),o=new Float32Array(n/2));for(var a=0,s=0;s<t.length;s++)i.set(t[s],a),a+=t[s].length;for(a=0,s=0;s<e.length;s++)o.set(e[s],a),a+=e[s].length;return{left:i,right:o}}(n,r,o,i),d=function(t,e,n,r,i,o){void 0===o&&(o=!0);var a=n>e?e:n,s=i,u=new ArrayBuffer(44+t.byteLength),l=new DataView(u),c=r,p=0;f(l,p,"RIFF"),p+=4,l.setUint32(p,36+t.byteLength,o),f(l,p+=4,"WAVE"),f(l,p+=4,"fmt "),p+=4,l.setUint32(p,16,o),p+=4,l.setUint16(p,1,o),p+=2,l.setUint16(p,c,o),p+=2,l.setUint32(p,a,o),p+=4,l.setUint32(p,c*a*(s/8),o),p+=4,l.setUint16(p,c*(s/8),o),p+=2,l.setUint16(p,s,o),f(l,p+=2,"data"),p+=4,l.setUint32(p,t.byteLength,o),p+=4;for(var d=0;d<t.byteLength;)l.setUint8(p,t.getUint8(d)),p++,d++;return l}(function(t,e,n){void 0===n&&(n=!0);var r=0,i=t.length*(e/8),o=new ArrayBuffer(i),a=new DataView(o);if(8===e)for(var s=0;s<t.length;s++,r++){var u=(l=Math.max(-1,Math.min(1,t[s])))<0?128*l:127*l;u=+u+128,a.setInt8(r,u)}else for(s=0;s<t.length;s++,r+=2){var l=Math.max(-1,Math.min(1,t[s]));a.setInt16(r,l<0?32768*l:32767*l,n)}return a}(function(t,e,n){for(var r=e/n,i=Math.max(r,1),o=t.left,a=t.right,s=Math.floor((o.length+a.length)/r),u=new Float32Array(s),l=0,c=0;l<s;){var f=Math.floor(c);u[l]=o[f],l++,a.length&&(u[l]=a[f],l++),c+=i}return u}({left:p.left,right:p.right},a,s),u,l),a,s,i,u,l);console.debug("处理好了数据",d),c(d)}},function(t,e,n){"use strict";n.r(e),n.d(e,"createAssistWorker",function(){return i});const r=t=>t instanceof ArrayBuffer||t instanceof MessagePort||self.ImageBitmap&&t instanceof ImageBitmap,i=()=>{const t=[];let e,n=new Map;const i={collect:t=>{for(let e in t)n.set(e,t[e]);return i},onMessage:t=>(e=t,i),create:i=>{const o=i.toString(),a=`\n // 将收集到的变量声明和定义加入脚本字符串,后面函数执行的时候便不会出现not defined的错误了\n ${Object.entries(Object.fromEntries(n)).reduce((t,[e,n])=>{return t+("function"==typeof n?`${e}=${n};`:`${e}=JSON.parse("${JSON.stringify(n)}");`)},"")}\n \n // 声明定义用于判断是否是可转移对象的函数\n $isTransferables = ${r}\n \n // 在脚本中声明并定义一个包含工作流程的函数体\n $job=${o};\n \n // 给worker线程添加消息监听,等待主线程的发号施令\n onmessage=e=>{\n const { index, args } = e.data;\n \n Promise.resolve(\n $job.apply($job, args.concat([{\n postMessage: (message) => postMessage({ type: 'WORKER_MESSAGE', message }),\n close: self.close,\n }]))\n ).then(result => {\n postMessage({ type: 'JOB_RESULT', message: { index, result } }, [result].filter($isTransferables))\n }).catch(error => {\n postMessage({ type: 'JOB_RESULT', message: { index, error } })\n })\n }\n `,s=URL.createObjectURL(new Blob([a],{type:"text/javascript"})),u=new Worker(s);u.onmessage=function(n){const r=n.data;if("WORKER_MESSAGE"===r.type&&e&&e.call(e,r.message),"JOB_RESULT"===r.type){const{index:e,result:n,error:i}=r.message,{done:o}=t[e];o(i,n)}};return{run:(...e)=>new Promise((n,i)=>{const o=t.length;t.push({done:(t,e)=>{t?i(t):n(e)}}),u.postMessage({index:o,args:e},e.filter(r))}),terminate:()=>{u.terminate(),URL.revokeObjectURL(s),t.length=0,n.clear(),e=void 0}}}};return i}}]).default});
//# sourceMappingURL=recorder.js.map