效果图:

实现代码:

<!DOCTYPE html>
<html><head><script src="recorder.js" type="text/javascript" charset="utf-8"></script><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover"><title></title><script src="https://cdn.jsdelivr.net/npm/vue"></script></head><body><div id="app"><input @click="startRecording()" type="button" value="录音" /><input @click="stopRecording()" type="button" value="停止" /><input @click="playRecording()" type="button" value="播放" /></div><script>let recorder = new Recorder();var audio = document.querySelector('audio');let app = new Vue({el: "#app",data: {txt: "1212"},mounted() {console.log('12121212')},methods: {startRecording() {console.log('1111')recorder.start();},stopRecording() {console.log('2222')recorder.stop();},playRecording() {console.log('33333')recorder.play(audio);}}})</script></body>
</html>

引入的 recorder.js 的代码:

/*!* * js-audio-recorder - js audio recorder plugin* * @version v1.0.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 n(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},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 i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(i,o,function(e){return t[e]}.bind(null,o));return i},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 i(t,e,n){for(var i=0;i<n.length;i++)t.setUint8(e+i,n.charCodeAt(i))}Object.defineProperty(e,"__esModule",{value:!0}),e.compress=function(t,e,n){for(var i=e/n,o=Math.max(i,1),r=t.left,a=t.right,s=Math.floor((r.length+a.length)/i),u=new Float32Array(s),c=0,l=0;c<s;){var f=Math.floor(l);u[c]=r[f],c++,a.length&&(u[c]=a[f],c++),l+=o}return u},e.encodePCM=function(t,e,n){void 0===n&&(n=!0);var i=0,o=t.length*(e/8),r=new ArrayBuffer(o),a=new DataView(r);if(8===e)for(var s=0;s<t.length;s++,i++){var u=(c=Math.max(-1,Math.min(1,t[s])))<0?128*c:127*c;u=+u+128,a.setInt8(i,u)}else for(s=0;s<t.length;s++,i+=2){var c=Math.max(-1,Math.min(1,t[s]));a.setInt16(i,c<0?32768*c:32767*c,n)}return a},e.encodeWAV=function(t,e,n,o,r,a){void 0===a&&(a=!0);var s=n>e?e:n,u=r,c=new ArrayBuffer(44+t.byteLength),l=new DataView(c),f=o,p=0;i(l,p,"RIFF"),p+=4,l.setUint32(p,36+t.byteLength,a),i(l,p+=4,"WAVE"),i(l,p+=4,"fmt "),p+=4,l.setUint32(p,16,a),p+=4,l.setUint16(p,1,a),p+=2,l.setUint16(p,f,a),p+=2,l.setUint32(p,s,a),p+=4,l.setUint32(p,f*s*(u/8),a),p+=4,l.setUint16(p,f*(u/8),a),p+=2,l.setUint16(p,u,a),i(l,p+=2,"data"),p+=4,l.setUint32(p,t.byteLength,a),p+=4;for(var d=0;d<t.byteLength;)l.setUint8(p,t.getUint8(d)),p++,d++;return l}},function(t,e,n){"use strict";var i,o=this&&this.__extends||(i=function(t,e){return(i=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}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var r=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 o(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(),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(),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();r.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();r.downloadWAV(e,t)},e}(n(5).default);e.default=u},function(t,e,n){"use strict";function i(t,e,n){var i=document.createElement("a");i.href=window.URL.createObjectURL(t),i.download=e+"."+n,i.click()}Object.defineProperty(e,"__esModule",{value:!0}),e.downloadWAV=function(t,e){void 0===e&&(e="recorder"),i(t,e,"wav")},e.downloadPCM=function(t,e){void 0===e&&(e="recorder"),i(t,e,"pcm")}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(4),o=null,r=0,a=0,s=null,u=null,c=null,l=!1,f=0,p=function(){};function d(){return l=!1,s.decodeAudioData(c.slice(0),function(t){(o=s.createBufferSource()).onended=function(){l||(f=s.currentTime-a+r,p())},o.buffer=t,o.connect(u),u.connect(s.destination),o.start(0,r),a=s.currentTime},function(t){i.throwError(t)})}function h(){o&&(o.stop(),o=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(),c=t,f=0,d()},t.pausePlay=function(){h(),r+=s.currentTime-a,l=!0},t.resumePlay=function(){return d()},t.stopPlay=function(){r=0,c=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=l?r:s.currentTime-a+r;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 i=n(0),o=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.needRecord=!0;var n,i=new(window.AudioContext||window.webkitAudioContext);this.inputSampleRate=i.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:~[11025,16e3,22050,24e3,44100,48e3].indexOf(t.sampleRate)?t.sampleRate:this.inputSampleRate,numChannels:~[1,2].indexOf(t.numChannels)?t.numChannels:1},this.outputSampleRate=this.config.sampleRate,this.oututSampleBits=this.config.sampleBits},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()},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,i=0;i<this.lBuffer.length;i++)t.set(this.lBuffer[i],n),n+=this.lBuffer[i].length;n=0;for(i=0;i<this.rBuffer.length;i++)e.set(this.rBuffer[i],n),n+=this.rBuffer[i].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.recorder.onaudioprocess=function(e){if(t.needRecord){var n,i=e.inputBuffer.getChannelData(0),o=null;t.lBuffer.push(new Float32Array(i)),t.size+=i.length,2===t.config.numChannels&&(o=e.inputBuffer.getChannelData(1),t.rBuffer.push(new Float32Array(o)),t.size+=o.length),t.fileSize=Math.floor(t.size/Math.max(t.inputSampleRate/t.outputSampleRate,1))*(t.oututSampleBits/8),n=100*Math.max.apply(Math,i),t.duration+=4096/t.inputSampleRate,t.onprocess&&t.onprocess(t.duration),t.onprogress&&t.onprogress({duration:t.duration,fileSize:t.fileSize,vol:n})}}},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,i){e.call(navigator,t,n,i)}):Promise.reject(new Error("浏览器不支持 getUserMedia !"))})},t.prototype.transformIntoPCM=function(t,e){var n=new Float32Array(t),o=new Float32Array(e),r=i.compress({left:n,right:o},this.inputSampleRate,this.outputSampleRate);return i.encodePCM(r,this.oututSampleBits,this.littleEdian)},t.getPermission=function(){return this.initUserMedia(),navigator.mediaDevices.getUserMedia({audio:!0}).then(function(t){t.getTracks().forEach(function(t){return t.stop()})})},t}();e.default=o}]).default});
//# sourceMappingURL=recorder.js.map

recorder说明:

使用方式 script方式

直接引入recorder.js即可

let recorder = new Recorder();

npm方式

安装:

npm i js-audio-recorder

调用:

import Recorder from 'js-audio-recorder';let recorder = new Recorder();

API 基本方法

// 开始录音
recorder.start();
// 暂停录音
recorder.pause();
// 继续录音
recorder.resume()
// 结束录音
recorder.stop();
// 录音播放
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);

默认配置

sampleBits,采样位数,默认是16
sampleRate,采样频率,浏览器默认的,我的chrome是48000
numChannels,声道数,默认是1

传入参数

new Recorder时支持传入参数,

{sampleBits: 16,         // 采样位数,范围8或16sampleRate: 16000,      // 采样率,范围11025、16000、22050、24000、44100、48000numChannels: 1,         // 声道,范围1或2
}

注意

使用127.0.0.1或localhost尝试,因为getUserMedia在高版本的chrome下需要使用https。

JS实现录音,播放完整代码带示例图相关推荐

  1. js html5 音乐播放器代码大全,js实现简单音乐播放器

    本文实例为大家分享了js实现音乐播放器的具体代码,供大家参考,具体内容如下 效果图: 可播放暂停继续播放,进度条可拖动,时间展示,声音调节 完整代码(直接拿来用) audio功能开发 * { marg ...

  2. Html+Css+Js五星好评(完整代码+详解)

    一,问题描述 当鼠标滑过空白的五颗星星时,有预览的颜色填充,当点击鼠标后,颜色填充确定,确定的颜色是绿色,当鼠标预览时,依然有预览色,没有点击鼠标确定时,颜色依然是,上一次的记录,点击了则是当次的好评 ...

  3. JS实现京东倒计时(完整代码)

    JS实现京东秒杀倒计时(完整代码) 一.获取图片 二.css实现外观 这里比较简单,就不细说了 三.JS实现倒计时 基本思路: 1.首先使用Date()对象获取当前时间(时间戳) 2.传递参数获取活动 ...

  4. 前端案例:像素鸟小游戏(js+dom操作,完整代码,附案例素材)

    目录 一.案例效果 二.实现思路 三.完整代码+详细注释 四.案例素材 一.案例效果 二.实现思路 创建游戏背景板和小鸟,并分别设置相对定位与绝对定位: 初始化背景图的位置: 初始化小鸟的位置: 设置 ...

  5. 小程序使用富文本完整代码及示例图

    先看示例图: 富文本html代码: 效果图: 实现步骤: 1.下载 wxParse代码放到你的小程序项目目录里面 https://github.com/icindy/wxParse 基本使用方法 Co ...

  6. 干货收藏!Python完整代码带你一文看懂抽样

    导读:抽样是从整体样本中通过一定的方法选择一部分样本.抽样是数据处理的基本步骤之一,也是科学实验.质量检验.社会调查普遍采用的一种经济有效的工作和研究方法. 作者:宋天龙 来源:大数据DT(ID:bi ...

  7. 91.video.ws index php_如何利用videojs实现视频列表循环播放(完整代码)

    本篇文章给大家带来的内容是关于如何利用videojs实现视频列表循环播放(完整代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 庭审直播 .video-js { /* posit ...

  8. 转:网页播放器代码全集

    源文地址:  http://blog.joingoo.com/pansir/logview_07041910280037.html 内容如下: 1.avi格式 代码片断如下: <object i ...

  9. 原生JS:100行js代码带你实现【像素鸟】小游戏(完整代码+素材图片)

    系列文章目录 JS:经典小游戏:像素鸟 JS:经典小游戏:贪吃蛇 JS:经典小游戏:扫雷 目录 系列文章目录 像素鸟 1.游戏介绍 2.代码分析 3.代码实现 3.1 随机生成水管 3.2 当水管超过 ...

最新文章

  1. 数据仓库中的维度表和事实表概述
  2. 【坑爹微信】微信开发基础 --- 微信快捷登陆问题解决
  3. js 获取时间戳的方法
  4. [Leetcode][第5458题][JAVA][字符串的好分割数目][双指针][HashSet]
  5. 2020-02-09 改udev硬件配置策略,改ETHTOOL_OPTS 或改 `/etc/NetworkManager/dispatcher.d/20-ethtool`...
  6. HTML5中最重要的技术点有哪些?
  7. fastjson jsonobject 转bean失败_挂面这么做,零失败,口感还是一顶一的棒
  8. 教你用报表工具搭建企业考核系统
  9. 史上最简单的土地利用转移矩阵分析(附练习数据下载)
  10. 从身份证获取出生年月日
  11. curl 输出接口请求响应时间
  12. java数字音频最强教程之音频的王者之路(音频发烧友篇)
  13. c语言提供了三种预处理命令,C语言提供的三种预处理命令
  14. Python 终极指南:进阶之路
  15. Microsoft Edge 开启 IE 模式
  16. 把金额类型转换成大写和英文
  17. SQL将一行多列数据合并成 一列
  18. 输出下三角数字阵列C语言
  19. linux多磁盘合并,挂载到相同文件夹
  20. Python面向对象项目练习:商品信息管理系统

热门文章

  1. 前端优化系列之一:dns预获取 dns-prefetch 提升页面载入速度
  2. 简单DP【p2642】双子序列最大和
  3. PLSQL创建Oracle定时任务
  4. 20162313苑洪铭 第一周作业
  5. 如何查找特定目录下最大的文件及文件夹
  6. 浏览器内核Trident/Gecko/WebKit/Presto
  7. Silverlight:SSL教程
  8. linux下查看内存使用情况
  9. ubuntu使用相关
  10. Jquery和javascript常用技巧