Logo

前端实现录音功能插件recorder.js

photo

2022年05月27日

recorder.js的使用详细解读

下面是recorder.js的源文件,可以直接复制粘贴使用

/*!
 * 
 * js-audio-recorder - js audio recorder plugin
 * 
 * @version v0.5.3
 * @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 i(n){if(e[n])return e[n].exports;var r=e[n]={i:n,l:!1,exports:{}};return t[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)i.d(n,r,function(e){return t[e]}.bind(null,r));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=0)}([function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t){void 0===t&&(t={}),this.isplaying=!1,this.lBuffer=[],this.rBuffer=[],this.tempPCM=[],this.inputSampleBits=16,this.playStamp=0,this.playTime=0,this.totalPlayTime=0,this.offset=0,this.fileSize=0;var e,i=new(window.AudioContext||window.webkitAudioContext);this.inputSampleRate=i.sampleRate,this.config={sampleBits:~[8,16].indexOf(t.sampleBits)?t.sampleBits:16,sampleRate:~[11025,16e3,22050,24e3,44100,48e3].indexOf(t.sampleRate)?t.sampleRate:this.inputSampleRate,numChannels:~[1,2].indexOf(t.numChannels)?t.numChannels:1,compiling:!!t.compiling||!1},this.outputSampleRate=this.config.sampleRate,this.oututSampleBits=this.config.sampleBits,this.littleEdian=(e=new ArrayBuffer(2),new DataView(e).setInt16(0,256,!0),256===new Int16Array(e)[0]),this.initUserMedia()}return t.prototype.initRecorder=function(){var t=this;this.context&&this.destroy(),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.recorder.onaudioprocess=function(e){if(t.isrecording&&!t.ispause){var i,n=e.inputBuffer.getChannelData(0),r=null;if(t.lBuffer.push(new Float32Array(n)),t.size+=n.length,2===t.config.numChannels&&(r=e.inputBuffer.getChannelData(1),t.rBuffer.push(new Float32Array(r)),t.size+=r.length),t.config.compiling){var o=t.transformIntoPCM(n,r);t.tempPCM.push(o),t.fileSize=o.byteLength*t.tempPCM.length}else t.fileSize=Math.floor(t.size/Math.max(t.inputSampleRate/t.outputSampleRate,1))*(t.oututSampleBits/8);i=100*Math.max.apply(Math,n),t.duration+=4096/t.inputSampleRate,t.onprocess&&t.onprocess(t.duration),t.onprogress&&t.onprogress({duration:t.duration,fileSize:t.fileSize,vol:i,data:t.tempPCM})}}},t.prototype.start=function(){var t=this;if(!this.isrecording)return this.clear(),this.initRecorder(),this.isrecording=!0,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.pause=function(){this.isrecording&&!this.ispause&&(this.ispause=!0,this.recorder.disconnect())},t.prototype.resume=function(){this.isrecording&&this.ispause&&(this.ispause=!1,this.audioInput&&this.audioInput.connect(this.analyser),this.analyser.connect(this.recorder),this.recorder.connect(this.context.destination))},t.prototype.stop=function(){this.isrecording=!1,this.audioInput&&this.audioInput.disconnect(),this.recorder.disconnect()},t.prototype.play=function(){this.stop(),this.source&&this.source.stop(),this.isplaying=!0,this.playTime=0,this.playAudioData()},t.prototype.getPlayTime=function(){var t=0;return(t=this.isplaying?this.context.currentTime-this.playStamp+this.playTime:this.playTime)>=this.totalPlayTime&&(t=this.totalPlayTime),t},t.prototype.pausePlay=function(){!this.isrecording&&this.isplaying&&(this.source&&this.source.disconnect(),this.playTime+=this.context.currentTime-this.playStamp,this.isplaying=!1)},t.prototype.resumePlay=function(){this.isrecording||this.isplaying||0===this.playTime||(this.isplaying=!0,this.playAudioData())},t.prototype.stopPlay=function(){this.isrecording||(this.playTime=0,this.isplaying=!1,this.source&&this.source.stop())},t.prototype.getWholeData=function(){return this.tempPCM},t.prototype.getNextData=function(){var t=this.tempPCM.length,e=this.tempPCM.slice(this.offset);return this.offset=t,e},t.prototype.playAudioData=function(){var e=this;this.context.decodeAudioData(this.getWAV().buffer,function(t){e.source=e.context.createBufferSource(),e.source.buffer=t,e.totalPlayTime=e.source.buffer.duration,e.source.connect(e.analyser),e.analyser.connect(e.context.destination),e.source.start(0,e.playTime),e.playStamp=e.context.currentTime},function(e){t.throwError(e)})},t.prototype.getRecordAnalyseData=function(){if(this.ispause)return this.prevDomainData;var t=new Uint8Array(this.analyser.frequencyBinCount);return this.analyser.getByteTimeDomainData(t),this.prevDomainData=t},t.prototype.getPlayAnalyseData=function(){return this.getRecordAnalyseData()},t.prototype.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(i,n){e.call(navigator,t,i,n)}):Promise.reject(new Error("浏览器不支持 getUserMedia !"))})},t.prototype.getPCM=function(){if(this.tempPCM.length){var e=new ArrayBuffer(this.tempPCM.length*this.tempPCM[0].byteLength),i=new DataView(e),n=0;this.tempPCM.forEach(function(t){for(var e=0,r=t.byteLength;e<r;++e)i.setInt8(n,t.getInt8(e)),n++}),this.PCM=i,this.tempPCM=[]}if(this.PCM)return this.PCM;var r=this.flat();return r=t.compress(r,this.inputSampleRate,this.outputSampleRate),this.PCM=t.encodePCM(r,this.oututSampleBits,this.littleEdian)},t.prototype.getPCMBlob=function(){return this.stop(),new Blob([this.getPCM()])},t.prototype.downloadPCM=function(t){void 0===t&&(t="recorder");var e=this.getPCMBlob();this.download(e,t,"pcm")},t.prototype.getWAV=function(){var e=this.getPCM();return t.encodeWAV(e,this.inputSampleRate,this.outputSampleRate,this.config.numChannels,this.oututSampleBits,this.littleEdian)},t.prototype.getWAVBlob=function(){return this.stop(),new Blob([this.getWAV()],{type:"audio/wav"})},t.prototype.downloadWAV=function(t){void 0===t&&(t="recorder");var e=this.getWAVBlob();this.download(e,t,"wav")},t.prototype.transformIntoPCM=function(e,i){var n=new Float32Array(e),r=new Float32Array(i),o=t.compress({left:n,right:r},this.inputSampleRate,this.outputSampleRate);return t.encodePCM(o,this.oututSampleBits,this.littleEdian)},t.prototype.destroy=function(){return this.stopStream(),this.closeAudioContext()},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.close?this.context.close():new Promise(function(t){t()})},t.prototype.download=function(e,i,n){try{var r=document.createElement("a");r.href=window.URL.createObjectURL(e),r.download=i+"."+n,r.click()}catch(e){t.throwError(e)}},t.prototype.clear=function(){this.lBuffer.length=0,this.rBuffer.length=0,this.size=0,this.fileSize=0,this.PCM=null,this.audioInput=null,this.duration=0,this.ispause=!1,this.isplaying=!1,this.playTime=0,this.totalPlayTime=0,this.source&&(this.source.stop(),this.source=null)},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 i=0,n=0;n<this.lBuffer.length;n++)t.set(this.lBuffer[n],i),i+=this.lBuffer[n].length;i=0;for(n=0;n<this.rBuffer.length;n++)e.set(this.rBuffer[n],i),i+=this.rBuffer[n].length;return{left:t,right:e}},t.playAudio=function(t){var e=document.createElement("audio");e.src=window.URL.createObjectURL(t),e.play()},t.compress=function(t,e,i){for(var n=e/i,r=Math.max(n,1),o=t.left,s=t.right,a=Math.floor((o.length+s.length)/n),u=new Float32Array(a),h=0,c=0;h<a;){var l=Math.floor(c);u[h]=o[l],h++,s.length&&(u[h]=s[l],h++),c+=r}return u},t.encodePCM=function(t,e,i){void 0===i&&(i=!0);var n=0,r=t.length*(e/8),o=new ArrayBuffer(r),s=new DataView(o);if(8===e)for(var a=0;a<t.length;a++,n++){var u=(h=Math.max(-1,Math.min(1,t[a])))<0?128*h:127*h;u=+u+128,s.setInt8(n,u)}else for(a=0;a<t.length;a++,n+=2){var h=Math.max(-1,Math.min(1,t[a]));s.setInt16(n,h<0?32768*h:32767*h,i)}return s},t.encodeWAV=function(t,e,i,n,o,s){void 0===s&&(s=!0);var a=i>e?e:i,u=o,h=new ArrayBuffer(44+t.byteLength),c=new DataView(h),l=n,p=0;r(c,p,"RIFF"),p+=4,c.setUint32(p,36+t.byteLength,s),r(c,p+=4,"WAVE"),r(c,p+=4,"fmt "),p+=4,c.setUint32(p,16,s),p+=4,c.setUint16(p,1,s),p+=2,c.setUint16(p,l,s),p+=2,c.setUint32(p,a,s),p+=4,c.setUint32(p,l*a*(u/8),s),p+=4,c.setUint16(p,l*(u/8),s),p+=2,c.setUint16(p,u,s),r(c,p+=2,"data"),p+=4,c.setUint32(p,t.byteLength,s),p+=4;for(var f=0;f<t.byteLength;)c.setUint8(p,t.getUint8(f)),p++,f++;return c},t.throwError=function(t){throw new Error(t)},t}();function r(t,e,i){for(var n=0;n<i.length;n++)t.setUint8(e+n,i.charCodeAt(n))}e.default=n}]).default});
//# sourceMappingURL=recorder.js.map

使用方法

//第一实例化,
let recorder = new Recorder({
        type:"wav",   //此处的type类型是可修改的
        bitRate:16,      
        sampleRate:16000,
        bufferSize:8192,
    })
//第二调用api方法

/**
 *
 *  
 * // 开始录音
 recorder.start();
 // 结束录音
 recorder.stop();
 // 暂停录音
 recorder.pause();

 // 继续录音
 recorder.resume()
 // 录音播放
 recorder.play();
 // 销毁录音实例,释放资源,fn为回调函数,
 recorder.destroy(fn);
 recorder = null;
 // 下载功能
 // 下载pcm文件
 recorder.downloadPCM();
 // 下载wav文件
 recorder.downloadWAV();
 // 重命名pcm文件,wav也支持
 recorder.downloadPCM('重命名');
 // 获取录音时长
 // 回调持续输出时长
 recorder.onprocess = function (duration) {
            console.log(duration);
        }
 // 手动获取录音时长
 console.log(recorder.duration);
//获取WAV音频文件
recorder.getWAVBlob()
//获取WAV音频文件MP4
recorder.getMP4Blob()
//获取WAV音频文件pcm
recorder.getPCMBlob()

*/
所有附件
该文章没有附件.
本文为原创文章,请注意保留出处!

最近闲来无事,便想着去了解一下长按录音功能,于是网上各种搜,但是都没有我想要的效果,于是决定干脆自己...recorder.js实现录音功能

热门文章

修复群晖Synology Drive client右键菜单缺失问题 本教程主要解决windows10右键菜单中没有SynologyDrive菜单的问题,整体思路是找到...修复群晖SynologyDriveclient右键菜单缺失问题 作者:Pastore Antonio
1821 浏览量
docker如何查看一个镜像内部的目录结构及其内部都有哪些文件 前言:有时候我们会在docker上下载一个镜像,或者是上传一个镜像到docker上,甚至有时候就是在...docker如何查看一个镜像内部的目录结构及其内部都有哪些文件 作者:Pastore Antonio
1803 浏览量
configure: error: Package requirements (oniguruma) were not met configure:error:Packagerequirements(oniguruma)...configure:error:Packagerequirements(oniguruma)werenotmet 作者:Pastore Antonio
1533 浏览量
Adobe Acrobat Pro 激活 这里记录了一些AdobeAcrobat的激活教程和组件。浏览量:1,686 作者:Pastore Antonio
1532 浏览量
追寻日出,找回自己 为什么我要去追寻日出?其实我是一个很懒的人,每次都起不来,直到有一次我在租房中睡到了大天亮,阳光照...追寻日出,找回自己 作者:Pastore Antonio
1509 浏览量