HZRecorder.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. (function (window) {
  2. //兼容
  3. window.URL = window.URL || window.webkitURL;
  4. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  5. var HZRecorder = function (stream, config) {
  6. config = config || {};
  7. config.sampleBits = config.sampleBits || 8; //采样数位 8, 16
  8. config.sampleRate = config.sampleRate || (44100 / 6); //采样率(1/6 44100)
  9. var context = new (window.webkitAudioContext || window.AudioContext)();
  10. var audioInput = context.createMediaStreamSource(stream);
  11. var createScript = context.createScriptProcessor || context.createJavaScriptNode;
  12. var recorder = createScript.apply(context, [4096, 1, 1]);
  13. var audioData = {
  14. size: 0 //录音文件长度
  15. , buffer: [] //录音缓存
  16. , inputSampleRate: context.sampleRate //输入采样率
  17. , inputSampleBits: 16 //输入采样数位 8, 16
  18. , outputSampleRate: config.sampleRate //输出采样率
  19. , oututSampleBits: config.sampleBits //输出采样数位 8, 16
  20. , input: function (data) {
  21. this.buffer.push(new Float32Array(data));
  22. this.size += data.length;
  23. }
  24. , compress: function () { //合并压缩
  25. //合并
  26. var data = new Float32Array(this.size);
  27. var offset = 0;
  28. for (var i = 0; i < this.buffer.length; i++) {
  29. data.set(this.buffer[i], offset);
  30. offset += this.buffer[i].length;
  31. }
  32. //压缩
  33. var compression = parseInt(this.inputSampleRate / this.outputSampleRate);
  34. var length = data.length / compression;
  35. var result = new Float32Array(length);
  36. var index = 0, j = 0;
  37. while (index < length) {
  38. result[index] = data[j];
  39. j += compression;
  40. index++;
  41. }
  42. return result;
  43. }
  44. , encodeWAV: function () {
  45. var sampleRate = Math.min(this.inputSampleRate, this.outputSampleRate);
  46. var sampleBits = Math.min(this.inputSampleBits, this.oututSampleBits);
  47. var bytes = this.compress();
  48. var dataLength = bytes.length * (sampleBits / 8);
  49. var buffer = new ArrayBuffer(44 + dataLength);
  50. var data = new DataView(buffer);
  51. var channelCount = 1;//单声道
  52. var offset = 0;
  53. var writeString = function (str) {
  54. for (var i = 0; i < str.length; i++) {
  55. data.setUint8(offset + i, str.charCodeAt(i));
  56. }
  57. }
  58. // 资源交换文件标识符
  59. writeString('RIFF'); offset += 4;
  60. // 下个地址开始到文件尾总字节数,即文件大小-8
  61. data.setUint32(offset, 36 + dataLength, true); offset += 4;
  62. // WAV文件标志
  63. writeString('WAVE'); offset += 4;
  64. // 波形格式标志
  65. writeString('fmt '); offset += 4;
  66. // 过滤字节,一般为 0x10 = 16
  67. data.setUint32(offset, 16, true); offset += 4;
  68. // 格式类别 (PCM形式采样数据)
  69. data.setUint16(offset, 1, true); offset += 2;
  70. // 通道数
  71. data.setUint16(offset, channelCount, true); offset += 2;
  72. // 采样率,每秒样本数,表示每个通道的播放速度
  73. data.setUint32(offset, sampleRate, true); offset += 4;
  74. // 波形数据传输率 (每秒平均字节数) 单声道×每秒数据位数×每样本数据位/8
  75. data.setUint32(offset, channelCount * sampleRate * (sampleBits / 8), true); offset += 4;
  76. // 快数据调整数 采样一次占用字节数 单声道×每样本的数据位数/8
  77. data.setUint16(offset, channelCount * (sampleBits / 8), true); offset += 2;
  78. // 每样本数据位数
  79. data.setUint16(offset, sampleBits, true); offset += 2;
  80. // 数据标识符
  81. writeString('data'); offset += 4;
  82. // 采样数据总数,即数据总大小-44
  83. data.setUint32(offset, dataLength, true); offset += 4;
  84. // 写入采样数据
  85. if (sampleBits === 8) {
  86. for (var i = 0; i < bytes.length; i++, offset++) {
  87. var s = Math.max(-1, Math.min(1, bytes[i]));
  88. var val = s < 0 ? s * 0x8000 : s * 0x7FFF;
  89. val = parseInt(255 / (65535 / (val + 32768)));
  90. data.setInt8(offset, val, true);
  91. }
  92. } else {
  93. for (var i = 0; i < bytes.length; i++, offset += 2) {
  94. var s = Math.max(-1, Math.min(1, bytes[i]));
  95. data.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
  96. }
  97. }
  98. return new Blob([data], { type: 'audio/mp3' });
  99. }
  100. };
  101. //开始录音
  102. this.start = function () {
  103. audioInput.connect(recorder);
  104. recorder.connect(context.destination);
  105. }
  106. //停止
  107. this.stop = function () {
  108. recorder.disconnect();
  109. }
  110. //获取音频文件
  111. this.getBlob = function () {
  112. this.stop();
  113. return audioData.encodeWAV();
  114. }
  115. //回放
  116. this.play = function (audio) {
  117. var downRec = document.getElementById("downloadRec");
  118. downRec.href = window.URL.createObjectURL(this.getBlob());
  119. downRec.download = new Date().toLocaleString()+".mp3";
  120. audio.src = window.URL.createObjectURL(this.getBlob());
  121. }
  122. //上传
  123. this.upload = function (url, callback) {
  124. var fd = new FormData();
  125. fd.append("audioData", this.getBlob());
  126. var xhr = new XMLHttpRequest();
  127. if (callback) {
  128. xhr.upload.addEventListener("progress", function (e) {
  129. callback('uploading', e);
  130. }, false);
  131. xhr.addEventListener("load", function (e) {
  132. callback('ok', e);
  133. }, false);
  134. xhr.addEventListener("error", function (e) {
  135. callback('error', e);
  136. }, false);
  137. xhr.addEventListener("abort", function (e) {
  138. callback('cancel', e);
  139. }, false);
  140. }
  141. xhr.open("POST", url);
  142. xhr.send(fd);
  143. }
  144. //音频采集
  145. recorder.onaudioprocess = function (e) {
  146. audioData.input(e.inputBuffer.getChannelData(0));
  147. //record(e.inputBuffer.getChannelData(0));
  148. }
  149. };
  150. //抛出异常
  151. HZRecorder.throwError = function (message) {
  152. alert(message);
  153. throw new function () { this.toString = function () { return message; } }
  154. }
  155. //是否支持录音
  156. HZRecorder.canRecording = (navigator.getUserMedia != null);
  157. //获取录音机
  158. HZRecorder.get = function (callback, config) {
  159. if (callback) {
  160. if (navigator.getUserMedia) {
  161. navigator.getUserMedia(
  162. { audio: true } //只启用音频
  163. , function (stream) {
  164. var rec = new HZRecorder(stream, config);
  165. callback(rec);
  166. }
  167. , function (error) {
  168. switch (error.code || error.name) {
  169. case 'PERMISSION_DENIED':
  170. case 'PermissionDeniedError':
  171. HZRecorder.throwError('用户拒绝提供信息。');
  172. break;
  173. case 'NOT_SUPPORTED_ERROR':
  174. case 'NotSupportedError':
  175. HZRecorder.throwError('浏览器不支持硬件设备。');
  176. break;
  177. case 'MANDATORY_UNSATISFIED_ERROR':
  178. case 'MandatoryUnsatisfiedError':
  179. HZRecorder.throwError('无法发现指定的硬件设备。');
  180. break;
  181. default:
  182. HZRecorder.throwError('无法打开麦克风。异常信息:' + (error.code || error.name));
  183. break;
  184. }
  185. });
  186. } else {
  187. HZRecorder.throwErr('当前浏览器不支持录音功能。'); return;
  188. }
  189. }
  190. }
  191. window.HZRecorder = HZRecorder;
  192. })(window);