recorder.js 18 KB

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