recorder.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Recorder = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. "use strict";
  3. module.exports = require("./recorder").Recorder;
  4. },{"./recorder":2}],2:[function(require,module,exports){
  5. 'use strict';
  6. var _createClass = (function () {
  7. function defineProperties(target, props) {
  8. for (var i = 0; i < props.length; i++) {
  9. var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
  10. }
  11. }return function (Constructor, protoProps, staticProps) {
  12. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  13. };
  14. })();
  15. Object.defineProperty(exports, "__esModule", {
  16. value: true
  17. });
  18. exports.Recorder = undefined;
  19. var _inlineWorker = require('inline-worker');
  20. var _inlineWorker2 = _interopRequireDefault(_inlineWorker);
  21. function _interopRequireDefault(obj) {
  22. return obj && obj.__esModule ? obj : { default: obj };
  23. }
  24. function _classCallCheck(instance, Constructor) {
  25. if (!(instance instanceof Constructor)) {
  26. throw new TypeError("Cannot call a class as a function");
  27. }
  28. }
  29. var Recorder = exports.Recorder = (function () {
  30. function Recorder(source, cfg) {
  31. var _this = this;
  32. _classCallCheck(this, Recorder);
  33. this.config = {
  34. bufferLen: 4096,
  35. numChannels: 2,
  36. mimeType: 'audio/wav'
  37. };
  38. this.recording = false;
  39. this.callbacks = {
  40. getBuffer: [],
  41. exportWAV: []
  42. };
  43. Object.assign(this.config, cfg);
  44. this.context = source.context;
  45. this.node = (this.context.createScriptProcessor || this.context.createJavaScriptNode).call(this.context, this.config.bufferLen, this.config.numChannels, this.config.numChannels);
  46. this.node.onaudioprocess = function (e) {
  47. if (!_this.recording) return;
  48. var buffer = [];
  49. for (var channel = 0; channel < _this.config.numChannels; channel++) {
  50. buffer.push(e.inputBuffer.getChannelData(channel));
  51. }
  52. _this.worker.postMessage({
  53. command: 'record',
  54. buffer: buffer
  55. });
  56. };
  57. source.connect(this.node);
  58. this.node.connect(this.context.destination); //this should not be necessary
  59. var self = {};
  60. this.worker = new _inlineWorker2.default(function () {
  61. var recLength = 0,
  62. recBuffers = [],
  63. sampleRate = undefined,
  64. numChannels = undefined;
  65. self.onmessage = function (e) {
  66. switch (e.data.command) {
  67. case 'init':
  68. init(e.data.config);
  69. break;
  70. case 'record':
  71. record(e.data.buffer);
  72. break;
  73. case 'exportWAV':
  74. exportWAV(e.data.type);
  75. break;
  76. case 'getBuffer':
  77. getBuffer();
  78. break;
  79. case 'clear':
  80. clear();
  81. break;
  82. }
  83. };
  84. function init(config) {
  85. sampleRate = config.sampleRate;
  86. numChannels = config.numChannels;
  87. initBuffers();
  88. }
  89. function record(inputBuffer) {
  90. for (var channel = 0; channel < numChannels; channel++) {
  91. recBuffers[channel].push(inputBuffer[channel]);
  92. }
  93. recLength += inputBuffer[0].length;
  94. }
  95. function exportWAV(type) {
  96. var buffers = [];
  97. for (var channel = 0; channel < numChannels; channel++) {
  98. buffers.push(mergeBuffers(recBuffers[channel], recLength));
  99. }
  100. var interleaved = undefined;
  101. if (numChannels === 2) {
  102. interleaved = interleave(buffers[0], buffers[1]);
  103. } else {
  104. interleaved = buffers[0];
  105. }
  106. var dataview = encodeWAV(interleaved);
  107. var audioBlob = new Blob([dataview], { type: type });
  108. self.postMessage({ command: 'exportWAV', data: audioBlob });
  109. }
  110. function getBuffer() {
  111. var buffers = [];
  112. for (var channel = 0; channel < numChannels; channel++) {
  113. buffers.push(mergeBuffers(recBuffers[channel], recLength));
  114. }
  115. self.postMessage({ command: 'getBuffer', data: buffers });
  116. }
  117. function clear() {
  118. recLength = 0;
  119. recBuffers = [];
  120. initBuffers();
  121. }
  122. function initBuffers() {
  123. for (var channel = 0; channel < numChannels; channel++) {
  124. recBuffers[channel] = [];
  125. }
  126. }
  127. function mergeBuffers(recBuffers, recLength) {
  128. var result = new Float32Array(recLength);
  129. var offset = 0;
  130. for (var i = 0; i < recBuffers.length; i++) {
  131. result.set(recBuffers[i], offset);
  132. offset += recBuffers[i].length;
  133. }
  134. return result;
  135. }
  136. function interleave(inputL, inputR) {
  137. var length = inputL.length + inputR.length;
  138. var result = new Float32Array(length);
  139. var index = 0,
  140. inputIndex = 0;
  141. while (index < length) {
  142. result[index++] = inputL[inputIndex];
  143. result[index++] = inputR[inputIndex];
  144. inputIndex++;
  145. }
  146. return result;
  147. }
  148. function floatTo16BitPCM(output, offset, input) {
  149. for (var i = 0; i < input.length; i++, offset += 2) {
  150. var s = Math.max(-1, Math.min(1, input[i]));
  151. output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
  152. }
  153. }
  154. function writeString(view, offset, string) {
  155. for (var i = 0; i < string.length; i++) {
  156. view.setUint8(offset + i, string.charCodeAt(i));
  157. }
  158. }
  159. function encodeWAV(samples) {
  160. var buffer = new ArrayBuffer(44 + samples.length * 2);
  161. var view = new DataView(buffer);
  162. /* RIFF identifier */
  163. writeString(view, 0, 'RIFF');
  164. /* RIFF chunk length */
  165. view.setUint32(4, 36 + samples.length * 2, true);
  166. /* RIFF type */
  167. writeString(view, 8, 'WAVE');
  168. /* format chunk identifier */
  169. writeString(view, 12, 'fmt ');
  170. /* format chunk length */
  171. view.setUint32(16, 16, true);
  172. /* sample format (raw) */
  173. view.setUint16(20, 1, true);
  174. /* channel count */
  175. view.setUint16(22, numChannels, true);
  176. /* sample rate */
  177. view.setUint32(24, sampleRate, true);
  178. /* byte rate (sample rate * block align) */
  179. view.setUint32(28, sampleRate * 4, true);
  180. /* block align (channel count * bytes per sample) */
  181. view.setUint16(32, numChannels * 2, true);
  182. /* bits per sample */
  183. view.setUint16(34, 16, true);
  184. /* data chunk identifier */
  185. writeString(view, 36, 'data');
  186. /* data chunk length */
  187. view.setUint32(40, samples.length * 2, true);
  188. floatTo16BitPCM(view, 44, samples);
  189. return view;
  190. }
  191. }, self);
  192. this.worker.postMessage({
  193. command: 'init',
  194. config: {
  195. sampleRate: this.context.sampleRate,
  196. numChannels: this.config.numChannels
  197. }
  198. });
  199. this.worker.onmessage = function (e) {
  200. var cb = _this.callbacks[e.data.command].pop();
  201. if (typeof cb == 'function') {
  202. cb(e.data.data);
  203. }
  204. };
  205. }
  206. _createClass(Recorder, [{
  207. key: 'record',
  208. value: function record() {
  209. this.recording = true;
  210. }
  211. }, {
  212. key: 'stop',
  213. value: function stop() {
  214. this.recording = false;
  215. }
  216. }, {
  217. key: 'clear',
  218. value: function clear() {
  219. this.worker.postMessage({ command: 'clear' });
  220. }
  221. }, {
  222. key: 'getBuffer',
  223. value: function getBuffer(cb) {
  224. cb = cb || this.config.callback;
  225. if (!cb) throw new Error('Callback not set');
  226. this.callbacks.getBuffer.push(cb);
  227. this.worker.postMessage({ command: 'getBuffer' });
  228. }
  229. }, {
  230. key: 'exportWAV',
  231. value: function exportWAV(cb, mimeType) {
  232. mimeType = mimeType || this.config.mimeType;
  233. cb = cb || this.config.callback;
  234. if (!cb) throw new Error('Callback not set');
  235. this.callbacks.exportWAV.push(cb);
  236. this.worker.postMessage({
  237. command: 'exportWAV',
  238. type: mimeType
  239. });
  240. }
  241. }], [{
  242. key: 'forceDownload',
  243. value: function forceDownload(blob, filename) {
  244. var url = (window.URL || window.webkitURL).createObjectURL(blob);
  245. var link = window.document.createElement('a');
  246. link.href = url;
  247. link.download = filename || 'output.wav';
  248. var click = document.createEvent("Event");
  249. click.initEvent("click", true, true);
  250. link.dispatchEvent(click);
  251. }
  252. }]);
  253. return Recorder;
  254. })();
  255. exports.default = Recorder;
  256. },{"inline-worker":3}],3:[function(require,module,exports){
  257. "use strict";
  258. module.exports = require("./inline-worker");
  259. },{"./inline-worker":4}],4:[function(require,module,exports){
  260. (function (global){
  261. "use strict";
  262. var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  263. var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
  264. var WORKER_ENABLED = !!(global === global.window && global.URL && global.Blob && global.Worker);
  265. var InlineWorker = (function () {
  266. function InlineWorker(func, self) {
  267. var _this = this;
  268. _classCallCheck(this, InlineWorker);
  269. if (WORKER_ENABLED) {
  270. var functionBody = func.toString().trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1];
  271. var url = global.URL.createObjectURL(new global.Blob([functionBody], { type: "text/javascript" }));
  272. return new global.Worker(url);
  273. }
  274. this.self = self;
  275. this.self.postMessage = function (data) {
  276. setTimeout(function () {
  277. _this.onmessage({ data: data });
  278. }, 0);
  279. };
  280. setTimeout(function () {
  281. func.call(self);
  282. }, 0);
  283. }
  284. _createClass(InlineWorker, {
  285. postMessage: {
  286. value: function postMessage(data) {
  287. var _this = this;
  288. setTimeout(function () {
  289. _this.self.onmessage({ data: data });
  290. }, 0);
  291. }
  292. }
  293. });
  294. return InlineWorker;
  295. })();
  296. module.exports = InlineWorker;
  297. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  298. },{}]},{},[1])(1)
  299. });