crunker 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/crunker.d.ts +1 -1
- package/dist/crunker.js +1 -1
- package/dist/crunker.js.map +1 -1
- package/examples/client/index.html +58 -59
- package/examples/server/index.html +32 -34
- package/package.json +2 -2
- package/src/crunker.ts +2 -2
package/dist/crunker.d.ts
CHANGED
package/dist/crunker.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Crunker",[],t):"object"==typeof exports?exports.Crunker=t():e.Crunker=t()}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";function r(e){return function(e){if(Array.isArray(e))return a(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return a(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}n.r(t),n.d(t,"default",(function(){return u}));var u=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.sampleRate,r=void 0===n?44100:n;o(this,e),this._sampleRate=r,this._context=this._createContext()}var t,n,a;return t=e,(n=[{key:"_createContext",value:function(){return window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext,new AudioContext}},{key:"fetchAudio",value:async function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return await Promise.all(n.map((async function(t){var n;return n=t instanceof File?await t.arrayBuffer():await fetch(t).then((function(e){return e.headers.has("Content-Type")&&!e.headers.get("Content-Type").includes("audio/")&&console.warn("Crunker: Attempted to fetch an audio file, but its MIME type is `".concat(e.headers.get("Content-Type").split(";")[0],"`. We'll try and continue anyway. (file: \"").concat(t,'")')),e.arrayBuffer()})),await e._context.decodeAudioData(n)})))}},{key:"mergeAudio",value:function(e){var t=this._context.createBuffer(this._maxNumberOfChannels(e),this._sampleRate*this._maxDuration(e),this._sampleRate);return e.forEach((function(e){for(var n=0;n<e.numberOfChannels;n++){for(var r=t.getChannelData(n),a=e.getChannelData(n),o=e.getChannelData(n).length-1;o>=0;o--)r[o]+=a[o];t.getChannelData(n).set(r)}})),t}},{key:"concatAudio",value:function(e){var t=this._context.createBuffer(this._maxNumberOfChannels(e),this._totalLength(e),this._sampleRate),n=0;return e.forEach((function(e){for(var r=0;r<e.numberOfChannels;r++)t.getChannelData(r).set(e.getChannelData(r),n);n+=e.length})),t}},{key:"padAudio",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(0===n)return e;if(t<0)throw new Error('Crunker: Parameter "padStart" in padAudio must be positive');if(n<0)throw new Error('Crunker: Parameter "seconds" in padAudio must be positive');for(var r=this._context.createBuffer(e.numberOfChannels,Math.ceil(e.length+n*e.sampleRate),e.sampleRate),a=0;a<e.numberOfChannels;a++){var o=e.getChannelData(a);r.getChannelData(a).set(o.subarray(0,Math.ceil(t*e.sampleRate)+1),0),r.getChannelData(a).set(o.subarray(Math.ceil(t*e.sampleRate)+2,r.length+1),Math.ceil((t+n)*e.sampleRate))}return r}},{key:"play",value:function(e){var t=this._context.createBufferSource();return t.buffer=e,t.connect(this._context.destination),t.start(),t}},{key:"export",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"audio/wav",n=this._interleave(e),r=this._writeHeaders(n),a=new Blob([r],{type:t});return{blob:a,url:this._renderURL(a),element:this._renderAudioElement(a)}}},{key:"download",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"crunker",n=document.createElement("a");return n.style.display="none",n.href=this._renderURL(e),n.download="".concat(t,".").concat(e.type.split("/")[1]),n.click(),n}},{key:"notSupported",value:function(e){return this._isSupported()?void 0:e()}},{key:"close",value:function(){return this._context.close(),this}},{key:"_maxDuration",value:function(e){return Math.max.apply(Math,r(e.map((function(e){return e.duration}))))}},{key:"_maxNumberOfChannels",value:function(e){return Math.max.apply(Math,r(e.map((function(e){return e.numberOfChannels}))))}},{key:"_totalLength",value:function(e){return e.map((function(e){return e.length})).reduce((function(e,t){return e+t}),0)}},{key:"_isSupported",value:function(){return"AudioContext"in window||"webkitAudioContext"in window||"mozAudioContext"in window}},{key:"_writeHeaders",value:function(e){var t=new ArrayBuffer(44+2*e.length),n=new DataView(t);return this._writeString(n,0,"RIFF"),n.setUint32(4,32+2*e.length,!0),this._writeString(n,8,"WAVE"),this._writeString(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,1,!0),n.setUint16(22,2,!0),n.setUint32(24,this._sampleRate,!0),n.setUint32(28,4*this._sampleRate,!0),n.setUint16(32,4,!0),n.setUint16(34,16,!0),this._writeString(n,36,"data"),n.setUint32(40,2*e.length,!0),this._floatTo16BitPCM(n,e,44)}},{key:"_floatTo16BitPCM",value:function(e,t,n){for(var r=0;r<t.length;r++,n+=2){var a=Math.max(-1,Math.min(1,t[r]));e.setInt16(n,a<0?32768*a:32767*a,!0)}return e}},{key:"_writeString",value:function(e,t,n){for(var r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}},{key:"_interleave",value:function(e){for(var t=e.getChannelData(0),n=2*t.length,r=new Float32Array(n),a=0,o=0;a<n;)r[a++]=t[o],r[a++]=t[o],o++;return r}},{key:"_renderAudioElement",value:function(e){var t=document.createElement("audio");return t.controls=!0,t.src=this._renderURL(e),t}},{key:"_renderURL",value:function(e){return(window.URL||window.webkitURL).createObjectURL(e)}}])&&i(t.prototype,n),a&&i(t,a),e}()}])}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Crunker",[],t):"object"==typeof exports?exports.Crunker=t():e.Crunker=t()}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";function r(e){return function(e){if(Array.isArray(e))return a(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return a(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}n.r(t),n.d(t,"default",(function(){return u}));var u=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.sampleRate,r=void 0===n?44100:n;o(this,e),this._sampleRate=r,this._context=this._createContext()}var t,n,a;return t=e,(n=[{key:"_createContext",value:function(){return window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext,new AudioContext}},{key:"fetchAudio",value:async function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return await Promise.all(n.map((async function(t){var n;return n=t instanceof File||t instanceof Blob?await t.arrayBuffer():await fetch(t).then((function(e){return e.headers.has("Content-Type")&&!e.headers.get("Content-Type").includes("audio/")&&console.warn("Crunker: Attempted to fetch an audio file, but its MIME type is `".concat(e.headers.get("Content-Type").split(";")[0],"`. We'll try and continue anyway. (file: \"").concat(t,'")')),e.arrayBuffer()})),await e._context.decodeAudioData(n)})))}},{key:"mergeAudio",value:function(e){var t=this._context.createBuffer(this._maxNumberOfChannels(e),this._sampleRate*this._maxDuration(e),this._sampleRate);return e.forEach((function(e){for(var n=0;n<e.numberOfChannels;n++){for(var r=t.getChannelData(n),a=e.getChannelData(n),o=e.getChannelData(n).length-1;o>=0;o--)r[o]+=a[o];t.getChannelData(n).set(r)}})),t}},{key:"concatAudio",value:function(e){var t=this._context.createBuffer(this._maxNumberOfChannels(e),this._totalLength(e),this._sampleRate),n=0;return e.forEach((function(e){for(var r=0;r<e.numberOfChannels;r++)t.getChannelData(r).set(e.getChannelData(r),n);n+=e.length})),t}},{key:"padAudio",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(0===n)return e;if(t<0)throw new Error('Crunker: Parameter "padStart" in padAudio must be positive');if(n<0)throw new Error('Crunker: Parameter "seconds" in padAudio must be positive');for(var r=this._context.createBuffer(e.numberOfChannels,Math.ceil(e.length+n*e.sampleRate),e.sampleRate),a=0;a<e.numberOfChannels;a++){var o=e.getChannelData(a);r.getChannelData(a).set(o.subarray(0,Math.ceil(t*e.sampleRate)+1),0),r.getChannelData(a).set(o.subarray(Math.ceil(t*e.sampleRate)+2,r.length+1),Math.ceil((t+n)*e.sampleRate))}return r}},{key:"play",value:function(e){var t=this._context.createBufferSource();return t.buffer=e,t.connect(this._context.destination),t.start(),t}},{key:"export",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"audio/wav",n=this._interleave(e),r=this._writeHeaders(n),a=new Blob([r],{type:t});return{blob:a,url:this._renderURL(a),element:this._renderAudioElement(a)}}},{key:"download",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"crunker",n=document.createElement("a");return n.style.display="none",n.href=this._renderURL(e),n.download="".concat(t,".").concat(e.type.split("/")[1]),n.click(),n}},{key:"notSupported",value:function(e){return this._isSupported()?void 0:e()}},{key:"close",value:function(){return this._context.close(),this}},{key:"_maxDuration",value:function(e){return Math.max.apply(Math,r(e.map((function(e){return e.duration}))))}},{key:"_maxNumberOfChannels",value:function(e){return Math.max.apply(Math,r(e.map((function(e){return e.numberOfChannels}))))}},{key:"_totalLength",value:function(e){return e.map((function(e){return e.length})).reduce((function(e,t){return e+t}),0)}},{key:"_isSupported",value:function(){return"AudioContext"in window||"webkitAudioContext"in window||"mozAudioContext"in window}},{key:"_writeHeaders",value:function(e){var t=new ArrayBuffer(44+2*e.length),n=new DataView(t);return this._writeString(n,0,"RIFF"),n.setUint32(4,32+2*e.length,!0),this._writeString(n,8,"WAVE"),this._writeString(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,1,!0),n.setUint16(22,2,!0),n.setUint32(24,this._sampleRate,!0),n.setUint32(28,4*this._sampleRate,!0),n.setUint16(32,4,!0),n.setUint16(34,16,!0),this._writeString(n,36,"data"),n.setUint32(40,2*e.length,!0),this._floatTo16BitPCM(n,e,44)}},{key:"_floatTo16BitPCM",value:function(e,t,n){for(var r=0;r<t.length;r++,n+=2){var a=Math.max(-1,Math.min(1,t[r]));e.setInt16(n,a<0?32768*a:32767*a,!0)}return e}},{key:"_writeString",value:function(e,t,n){for(var r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}},{key:"_interleave",value:function(e){for(var t=e.getChannelData(0),n=2*t.length,r=new Float32Array(n),a=0,o=0;a<n;)r[a++]=t[o],r[a++]=t[o],o++;return r}},{key:"_renderAudioElement",value:function(e){var t=document.createElement("audio");return t.controls=!0,t.src=this._renderURL(e),t}},{key:"_renderURL",value:function(e){return(window.URL||window.webkitURL).createObjectURL(e)}}])&&i(t.prototype,n),a&&i(t,a),e}()}])}));
|
|
2
2
|
//# sourceMappingURL=crunker.js.map
|
package/dist/crunker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["webpack://Crunker/webpack/universalModuleDefinition","webpack://Crunker/webpack/bootstrap","webpack://Crunker/./crunker.ts"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Crunker","sampleRate","this","_sampleRate","_context","_createContext","AudioContext","webkitAudioContext","mozAudioContext","async","filepaths","Promise","all","map","filepath","buffer","File","arrayBuffer","fetch","then","response","headers","has","includes","console","warn","split","decodeAudioData","buffers","output","createBuffer","_maxNumberOfChannels","_maxDuration","forEach","channelNumber","numberOfChannels","outputData","getChannelData","bufferData","length","set","_totalLength","offset","padStart","seconds","Error","updatedBuffer","Math","ceil","channelData","subarray","source","createBufferSource","connect","destination","start","type","recorded","_interleave","dataview","_writeHeaders","audioBlob","Blob","blob","url","_renderURL","element","_renderAudioElement","filename","a","document","createElement","style","display","href","download","click","callback","_isSupported","undefined","close","max","duration","reduce","b","ArrayBuffer","view","DataView","_writeString","setUint32","setUint16","_floatTo16BitPCM","tmp","min","setInt16","header","setUint8","charCodeAt","input","result","Float32Array","index","inputIndex","audio","controls","src","URL","webkitURL","createObjectURL"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,UAAW,GAAIH,GACI,iBAAZC,QACdA,QAAiB,QAAID,IAErBD,EAAc,QAAIC,IARpB,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,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BAQT,SAAmBxC,GACjB,OAAQnG,OAAO8I,KAAO9I,OAAO+I,WAAWC,gBAAgB7C,Q","file":"crunker.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"Crunker\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Crunker\"] = factory();\n\telse\n\t\troot[\"Crunker\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export interface CrunkerConstructorOptions {\n /**\n * Sample rate for Crunker's internal audio context.\n *\n * @default 44100\n */\n sampleRate: number;\n}\n\nexport type CrunkerInputTypes = string | File;\n\n/**\n * An exported Crunker audio object.\n */\nexport interface ExportedCrunkerAudio {\n blob: Blob;\n url: string;\n element: HTMLAudioElement;\n}\n\n/**\n * Crunker is the simple way to merge, concatenate, play, export and download audio files using the Web Audio API.\n */\nexport default class Crunker {\n private readonly _sampleRate: number;\n private readonly _context: AudioContext;\n\n /**\n * Creates a new instance of Crunker with the provided options.\n */\n constructor({ sampleRate = 44100 }: Partial<CrunkerConstructorOptions> = {}) {\n this._sampleRate = sampleRate;\n this._context = this._createContext();\n }\n\n /**\n * Creates Crunker's internal AudioContext.\n *\n * @internal\n */\n private _createContext(): AudioContext {\n window.AudioContext = window.AudioContext || (window as any).webkitAudioContext || (window as any).mozAudioContext;\n return new AudioContext();\n }\n\n /**\n * Asynchronously fetches multiple audio files and returns an array of AudioBuffers.\n */\n async fetchAudio(...filepaths: CrunkerInputTypes[]): Promise<AudioBuffer[]> {\n return await Promise.all(\n filepaths.map(async (filepath) => {\n let buffer: ArrayBuffer;\n\n if (filepath instanceof File) {\n buffer = await filepath.arrayBuffer();\n } else {\n buffer = await fetch(filepath).then((response) => {\n if (response.headers.has('Content-Type') && !response.headers.get('Content-Type')!.includes('audio/')) {\n console.warn(\n `Crunker: Attempted to fetch an audio file, but its MIME type is \\`${\n response.headers.get('Content-Type')!.split(';')[0]\n }\\`. We'll try and continue anyway. (file: \"${filepath}\")`\n );\n }\n\n return response.arrayBuffer();\n });\n }\n\n return await this._context.decodeAudioData(buffer);\n })\n );\n }\n\n /**\n * Merges (layers) multiple AudioBuffers into a single AudioBuffer.\n *\n * **Visual representation:**\n *\n * \n */\n mergeAudio(buffers: AudioBuffer[]): AudioBuffer {\n const output = this._context.createBuffer(\n this._maxNumberOfChannels(buffers),\n this._sampleRate * this._maxDuration(buffers),\n this._sampleRate\n );\n\n buffers.forEach((buffer) => {\n for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {\n const outputData = output.getChannelData(channelNumber);\n const bufferData = buffer.getChannelData(channelNumber);\n\n for (let i = buffer.getChannelData(channelNumber).length - 1; i >= 0; i--) {\n outputData[i] += bufferData[i];\n }\n\n output.getChannelData(channelNumber).set(outputData);\n }\n });\n\n return output;\n }\n\n /**\n * Concatenates multiple AudioBuffers into a single AudioBuffer.\n *\n * **Visual representation:**\n *\n * \n */\n concatAudio(buffers: AudioBuffer[]): AudioBuffer {\n const output = this._context.createBuffer(\n this._maxNumberOfChannels(buffers),\n this._totalLength(buffers),\n this._sampleRate\n );\n let offset = 0;\n\n buffers.forEach((buffer) => {\n for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {\n output.getChannelData(channelNumber).set(buffer.getChannelData(channelNumber), offset);\n }\n\n offset += buffer.length;\n });\n\n return output;\n }\n\n /**\n * Pads a specified AudioBuffer with silence from a specified start time,\n * for a specified length of time.\n *\n * Accepts float values as well as whole integers.\n *\n * @param buffer AudioBuffer to pad\n * @param padStart Time to start padding (in seconds)\n * @param seconds Duration to pad for (in seconds)\n */\n padAudio(buffer: AudioBuffer, padStart: number = 0, seconds: number = 0): AudioBuffer {\n if (seconds === 0) return buffer;\n\n if (padStart < 0) throw new Error('Crunker: Parameter \"padStart\" in padAudio must be positive');\n if (seconds < 0) throw new Error('Crunker: Parameter \"seconds\" in padAudio must be positive');\n\n const updatedBuffer = this._context.createBuffer(\n buffer.numberOfChannels,\n Math.ceil(buffer.length + seconds * buffer.sampleRate),\n buffer.sampleRate\n );\n\n for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {\n const channelData = buffer.getChannelData(channelNumber);\n updatedBuffer\n .getChannelData(channelNumber)\n .set(channelData.subarray(0, Math.ceil(padStart * buffer.sampleRate) + 1), 0);\n\n updatedBuffer\n .getChannelData(channelNumber)\n .set(\n channelData.subarray(Math.ceil(padStart * buffer.sampleRate) + 2, updatedBuffer.length + 1),\n Math.ceil((padStart + seconds) * buffer.sampleRate)\n );\n }\n\n return updatedBuffer;\n }\n\n /**\n * Plays the provided AudioBuffer in an AudioBufferSourceNode.\n */\n play(buffer: AudioBuffer): AudioBufferSourceNode {\n const source = this._context.createBufferSource();\n\n source.buffer = buffer;\n source.connect(this._context.destination);\n source.start();\n\n return source;\n }\n\n /**\n * Exports the specified AudioBuffer to a Blob, Object URI and HTMLAudioElement.\n *\n * Note that changing the MIME type does not change the actual file format. The\n * file format will **always** be a WAVE file due to how audio is stored in the\n * browser.\n *\n * @param buffer Buffer to export\n * @param type MIME type (default: `audio/wav`)\n */\n export(buffer: AudioBuffer, type: string = 'audio/wav'): ExportedCrunkerAudio {\n const recorded = this._interleave(buffer);\n const dataview = this._writeHeaders(recorded);\n const audioBlob = new Blob([dataview], { type });\n\n return {\n blob: audioBlob,\n url: this._renderURL(audioBlob),\n element: this._renderAudioElement(audioBlob),\n };\n }\n\n /**\n * Downloads the provided Blob.\n *\n * @param blob Blob to download\n * @param filename An optional file name to use for the download (default: `crunker`)\n */\n download(blob: Blob, filename: string = 'crunker'): HTMLAnchorElement {\n const a = document.createElement('a');\n\n a.style.display = 'none';\n a.href = this._renderURL(blob);\n a.download = `${filename}.${blob.type.split('/')[1]}`;\n a.click();\n\n return a;\n }\n\n /**\n * Executes a callback if the browser does not support the Web Audio API.\n *\n * Returns the result of the callback, or `undefined` if the Web Audio API is supported.\n *\n * @param callback callback to run if the browser does not support the Web Audio API\n */\n notSupported<T>(callback: () => T): T | undefined {\n return this._isSupported() ? undefined : callback();\n }\n\n /**\n * Closes Crunker's internal AudioContext.\n */\n close(): this {\n this._context.close();\n return this;\n }\n\n /**\n * Returns the largest duration of the longest AudioBuffer.\n *\n * @internal\n */\n private _maxDuration(buffers: AudioBuffer[]): number {\n return Math.max(...buffers.map((buffer) => buffer.duration));\n }\n\n /**\n * Returns the largest number of channels in an array of AudioBuffers.\n *\n * @internal\n */\n private _maxNumberOfChannels(buffers: AudioBuffer[]): number {\n return Math.max(...buffers.map((buffer) => buffer.numberOfChannels));\n }\n\n /**\n * Returns the sum of the lengths of an array of AudioBuffers.\n *\n * @internal\n */\n private _totalLength(buffers: AudioBuffer[]): number {\n return buffers.map((buffer) => buffer.length).reduce((a, b) => a + b, 0);\n }\n\n /**\n * Returns whether the browser supports the Web Audio API.\n *\n * @internal\n */\n private _isSupported(): boolean {\n return 'AudioContext' in window || 'webkitAudioContext' in window || 'mozAudioContext' in window;\n }\n\n /**\n * Writes the WAV headers for the specified Float32Array.\n *\n * Returns a DataView containing the WAV headers and file content.\n *\n * @internal\n */\n private _writeHeaders(buffer: Float32Array): DataView {\n const arrayBuffer = new ArrayBuffer(44 + buffer.length * 2);\n const view = new DataView(arrayBuffer);\n\n this._writeString(view, 0, 'RIFF');\n view.setUint32(4, 32 + buffer.length * 2, true);\n this._writeString(view, 8, 'WAVE');\n this._writeString(view, 12, 'fmt ');\n view.setUint32(16, 16, true);\n view.setUint16(20, 1, true);\n view.setUint16(22, 2, true);\n view.setUint32(24, this._sampleRate, true);\n view.setUint32(28, this._sampleRate * 4, true);\n view.setUint16(32, 4, true);\n view.setUint16(34, 16, true);\n this._writeString(view, 36, 'data');\n view.setUint32(40, buffer.length * 2, true);\n\n return this._floatTo16BitPCM(view, buffer, 44);\n }\n\n /**\n * Converts a Float32Array to 16-bit PCM.\n *\n * @internal\n */\n private _floatTo16BitPCM(dataview: DataView, buffer: Float32Array, offset: number): DataView {\n for (let i = 0; i < buffer.length; i++, offset += 2) {\n const tmp = Math.max(-1, Math.min(1, buffer[i]));\n dataview.setInt16(offset, tmp < 0 ? tmp * 0x8000 : tmp * 0x7fff, true);\n }\n\n return dataview;\n }\n\n /**\n * Writes a string to a DataView at the specified offset.\n *\n * @internal\n */\n private _writeString(dataview: DataView, offset: number, header: string): void {\n for (let i = 0; i < header.length; i++) {\n dataview.setUint8(offset + i, header.charCodeAt(i));\n }\n }\n\n /**\n * Converts an AudioBuffer to a Float32Array.\n *\n * @internal\n */\n private _interleave(input: AudioBuffer): Float32Array {\n const buffer = input.getChannelData(0),\n length = buffer.length * 2,\n result = new Float32Array(length);\n\n let index = 0,\n inputIndex = 0;\n\n while (index < length) {\n result[index++] = buffer[inputIndex];\n result[index++] = buffer[inputIndex];\n inputIndex++;\n }\n return result;\n }\n\n /**\n * Creates an HTMLAudioElement whose source is the specified Blob.\n *\n * @internal\n */\n private _renderAudioElement(blob: Blob): HTMLAudioElement {\n const audio = document.createElement('audio');\n\n audio.controls = true;\n audio.src = this._renderURL(blob);\n\n return audio;\n }\n\n /**\n * Creates an Object URL for the specified Blob.\n *\n * @internal\n */\n private _renderURL(blob: Blob): string {\n return (window.URL || window.webkitURL).createObjectURL(blob);\n }\n}\n"],"sourceRoot":""}
|
|
1
|
+
{"version":3,"sources":["webpack://Crunker/webpack/universalModuleDefinition","webpack://Crunker/webpack/bootstrap","webpack://Crunker/./crunker.ts"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Crunker","sampleRate","this","_sampleRate","_context","_createContext","AudioContext","webkitAudioContext","mozAudioContext","async","filepaths","Promise","all","map","filepath","buffer","File","Blob","arrayBuffer","fetch","then","response","headers","has","includes","console","warn","split","decodeAudioData","buffers","output","createBuffer","_maxNumberOfChannels","_maxDuration","forEach","channelNumber","numberOfChannels","outputData","getChannelData","bufferData","length","set","_totalLength","offset","padStart","seconds","Error","updatedBuffer","Math","ceil","channelData","subarray","source","createBufferSource","connect","destination","start","type","recorded","_interleave","dataview","_writeHeaders","audioBlob","blob","url","_renderURL","element","_renderAudioElement","filename","a","document","createElement","style","display","href","download","click","callback","_isSupported","undefined","close","max","duration","reduce","b","ArrayBuffer","view","DataView","_writeString","setUint32","setUint16","_floatTo16BitPCM","tmp","min","setInt16","header","setUint8","charCodeAt","input","result","Float32Array","index","inputIndex","audio","controls","src","URL","webkitURL","createObjectURL"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,UAAW,GAAIH,GACI,iBAAZC,QACdA,QAAiB,QAAID,IAErBD,EAAc,QAAIC,IARpB,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df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B,GACzCmF,EAAKI,UAAU,GAAI,GAAG,GACtBJ,EAAKI,UAAU,GAAI,IAAI,GACvBxF,KAAKsF,aAAaF,EAAM,GAAI,QAC5BA,EAAKG,UAAU,GAAoB,EAAhB1E,EAAOyB,QAAY,GAE/BtC,KAAKyF,iBAAiBL,EAAMvE,EAAQ,M,8BAQ7C,SAAyB6C,EAAoB7C,EAAsB4B,GACjE,IAAK,IAAI3E,EAAI,EAAGA,EAAI+C,EAAOyB,OAAQxE,IAAK2E,GAAU,EAAG,CACnD,IAAMiD,EAAM5C,KAAKiC,KAAK,EAAGjC,KAAK6C,IAAI,EAAG9E,EAAO/C,KAC5C4F,EAASkC,SAASnD,EAAQiD,EAAM,EAAU,MAANA,EAAqB,MAANA,GAAc,GAGnE,OAAOhC,I,0BAQT,SAAqBA,EAAoBjB,EAAgBoD,GACvD,IAAK,IAAI/H,EAAI,EAAGA,EAAI+H,EAAOvD,OAAQxE,IACjC4F,EAASoC,SAASrD,EAAS3E,EAAG+H,EAAOE,WAAWjI,M,yBASpD,SAAoBkI,GAQlB,IAPA,IAAMnF,EAASmF,EAAM5D,eAAe,GAClCE,EAAyB,EAAhBzB,EAAOyB,OAChB2D,EAAS,IAAIC,aAAa5D,GAExB6D,EAAQ,EACVC,EAAa,EAERD,EAAQ7D,GACb2D,EAAOE,KAAWtF,EAAOuF,GACzBH,EAAOE,KAAWtF,EAAOuF,GACzBA,IAEF,OAAOH,I,iCAQT,SAA4BpC,GAC1B,IAAMwC,EAAQjC,SAASC,cAAc,SAKrC,OAHAgC,EAAMC,UAAW,EACjBD,EAAME,IAAMvG,KAAK+D,WAAWF,GAErBwC,I,wBAQT,SAAmBxC,GACjB,OAAQnG,OAAO8I,KAAO9I,OAAO+I,WAAWC,gBAAgB7C,Q","file":"crunker.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"Crunker\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Crunker\"] = factory();\n\telse\n\t\troot[\"Crunker\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export interface CrunkerConstructorOptions {\n /**\n * Sample rate for Crunker's internal audio context.\n *\n * @default 44100\n */\n sampleRate: number;\n}\n\nexport type CrunkerInputTypes = string | File | Blob;\n\n/**\n * An exported Crunker audio object.\n */\nexport interface ExportedCrunkerAudio {\n blob: Blob;\n url: string;\n element: HTMLAudioElement;\n}\n\n/**\n * Crunker is the simple way to merge, concatenate, play, export and download audio files using the Web Audio API.\n */\nexport default class Crunker {\n private readonly _sampleRate: number;\n private readonly _context: AudioContext;\n\n /**\n * Creates a new instance of Crunker with the provided options.\n */\n constructor({ sampleRate = 44100 }: Partial<CrunkerConstructorOptions> = {}) {\n this._sampleRate = sampleRate;\n this._context = this._createContext();\n }\n\n /**\n * Creates Crunker's internal AudioContext.\n *\n * @internal\n */\n private _createContext(): AudioContext {\n window.AudioContext = window.AudioContext || (window as any).webkitAudioContext || (window as any).mozAudioContext;\n return new AudioContext();\n }\n\n /**\n * Asynchronously fetches multiple audio files and returns an array of AudioBuffers.\n */\n async fetchAudio(...filepaths: CrunkerInputTypes[]): Promise<AudioBuffer[]> {\n return await Promise.all(\n filepaths.map(async (filepath) => {\n let buffer: ArrayBuffer;\n\n if (filepath instanceof File || filepath instanceof Blob) {\n buffer = await filepath.arrayBuffer();\n } else {\n buffer = await fetch(filepath).then((response) => {\n if (response.headers.has('Content-Type') && !response.headers.get('Content-Type')!.includes('audio/')) {\n console.warn(\n `Crunker: Attempted to fetch an audio file, but its MIME type is \\`${\n response.headers.get('Content-Type')!.split(';')[0]\n }\\`. We'll try and continue anyway. (file: \"${filepath}\")`\n );\n }\n\n return response.arrayBuffer();\n });\n }\n\n return await this._context.decodeAudioData(buffer);\n })\n );\n }\n\n /**\n * Merges (layers) multiple AudioBuffers into a single AudioBuffer.\n *\n * **Visual representation:**\n *\n * \n */\n mergeAudio(buffers: AudioBuffer[]): AudioBuffer {\n const output = this._context.createBuffer(\n this._maxNumberOfChannels(buffers),\n this._sampleRate * this._maxDuration(buffers),\n this._sampleRate\n );\n\n buffers.forEach((buffer) => {\n for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {\n const outputData = output.getChannelData(channelNumber);\n const bufferData = buffer.getChannelData(channelNumber);\n\n for (let i = buffer.getChannelData(channelNumber).length - 1; i >= 0; i--) {\n outputData[i] += bufferData[i];\n }\n\n output.getChannelData(channelNumber).set(outputData);\n }\n });\n\n return output;\n }\n\n /**\n * Concatenates multiple AudioBuffers into a single AudioBuffer.\n *\n * **Visual representation:**\n *\n * \n */\n concatAudio(buffers: AudioBuffer[]): AudioBuffer {\n const output = this._context.createBuffer(\n this._maxNumberOfChannels(buffers),\n this._totalLength(buffers),\n this._sampleRate\n );\n let offset = 0;\n\n buffers.forEach((buffer) => {\n for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {\n output.getChannelData(channelNumber).set(buffer.getChannelData(channelNumber), offset);\n }\n\n offset += buffer.length;\n });\n\n return output;\n }\n\n /**\n * Pads a specified AudioBuffer with silence from a specified start time,\n * for a specified length of time.\n *\n * Accepts float values as well as whole integers.\n *\n * @param buffer AudioBuffer to pad\n * @param padStart Time to start padding (in seconds)\n * @param seconds Duration to pad for (in seconds)\n */\n padAudio(buffer: AudioBuffer, padStart: number = 0, seconds: number = 0): AudioBuffer {\n if (seconds === 0) return buffer;\n\n if (padStart < 0) throw new Error('Crunker: Parameter \"padStart\" in padAudio must be positive');\n if (seconds < 0) throw new Error('Crunker: Parameter \"seconds\" in padAudio must be positive');\n\n const updatedBuffer = this._context.createBuffer(\n buffer.numberOfChannels,\n Math.ceil(buffer.length + seconds * buffer.sampleRate),\n buffer.sampleRate\n );\n\n for (let channelNumber = 0; channelNumber < buffer.numberOfChannels; channelNumber++) {\n const channelData = buffer.getChannelData(channelNumber);\n updatedBuffer\n .getChannelData(channelNumber)\n .set(channelData.subarray(0, Math.ceil(padStart * buffer.sampleRate) + 1), 0);\n\n updatedBuffer\n .getChannelData(channelNumber)\n .set(\n channelData.subarray(Math.ceil(padStart * buffer.sampleRate) + 2, updatedBuffer.length + 1),\n Math.ceil((padStart + seconds) * buffer.sampleRate)\n );\n }\n\n return updatedBuffer;\n }\n\n /**\n * Plays the provided AudioBuffer in an AudioBufferSourceNode.\n */\n play(buffer: AudioBuffer): AudioBufferSourceNode {\n const source = this._context.createBufferSource();\n\n source.buffer = buffer;\n source.connect(this._context.destination);\n source.start();\n\n return source;\n }\n\n /**\n * Exports the specified AudioBuffer to a Blob, Object URI and HTMLAudioElement.\n *\n * Note that changing the MIME type does not change the actual file format. The\n * file format will **always** be a WAVE file due to how audio is stored in the\n * browser.\n *\n * @param buffer Buffer to export\n * @param type MIME type (default: `audio/wav`)\n */\n export(buffer: AudioBuffer, type: string = 'audio/wav'): ExportedCrunkerAudio {\n const recorded = this._interleave(buffer);\n const dataview = this._writeHeaders(recorded);\n const audioBlob = new Blob([dataview], { type });\n\n return {\n blob: audioBlob,\n url: this._renderURL(audioBlob),\n element: this._renderAudioElement(audioBlob),\n };\n }\n\n /**\n * Downloads the provided Blob.\n *\n * @param blob Blob to download\n * @param filename An optional file name to use for the download (default: `crunker`)\n */\n download(blob: Blob, filename: string = 'crunker'): HTMLAnchorElement {\n const a = document.createElement('a');\n\n a.style.display = 'none';\n a.href = this._renderURL(blob);\n a.download = `${filename}.${blob.type.split('/')[1]}`;\n a.click();\n\n return a;\n }\n\n /**\n * Executes a callback if the browser does not support the Web Audio API.\n *\n * Returns the result of the callback, or `undefined` if the Web Audio API is supported.\n *\n * @param callback callback to run if the browser does not support the Web Audio API\n */\n notSupported<T>(callback: () => T): T | undefined {\n return this._isSupported() ? undefined : callback();\n }\n\n /**\n * Closes Crunker's internal AudioContext.\n */\n close(): this {\n this._context.close();\n return this;\n }\n\n /**\n * Returns the largest duration of the longest AudioBuffer.\n *\n * @internal\n */\n private _maxDuration(buffers: AudioBuffer[]): number {\n return Math.max(...buffers.map((buffer) => buffer.duration));\n }\n\n /**\n * Returns the largest number of channels in an array of AudioBuffers.\n *\n * @internal\n */\n private _maxNumberOfChannels(buffers: AudioBuffer[]): number {\n return Math.max(...buffers.map((buffer) => buffer.numberOfChannels));\n }\n\n /**\n * Returns the sum of the lengths of an array of AudioBuffers.\n *\n * @internal\n */\n private _totalLength(buffers: AudioBuffer[]): number {\n return buffers.map((buffer) => buffer.length).reduce((a, b) => a + b, 0);\n }\n\n /**\n * Returns whether the browser supports the Web Audio API.\n *\n * @internal\n */\n private _isSupported(): boolean {\n return 'AudioContext' in window || 'webkitAudioContext' in window || 'mozAudioContext' in window;\n }\n\n /**\n * Writes the WAV headers for the specified Float32Array.\n *\n * Returns a DataView containing the WAV headers and file content.\n *\n * @internal\n */\n private _writeHeaders(buffer: Float32Array): DataView {\n const arrayBuffer = new ArrayBuffer(44 + buffer.length * 2);\n const view = new DataView(arrayBuffer);\n\n this._writeString(view, 0, 'RIFF');\n view.setUint32(4, 32 + buffer.length * 2, true);\n this._writeString(view, 8, 'WAVE');\n this._writeString(view, 12, 'fmt ');\n view.setUint32(16, 16, true);\n view.setUint16(20, 1, true);\n view.setUint16(22, 2, true);\n view.setUint32(24, this._sampleRate, true);\n view.setUint32(28, this._sampleRate * 4, true);\n view.setUint16(32, 4, true);\n view.setUint16(34, 16, true);\n this._writeString(view, 36, 'data');\n view.setUint32(40, buffer.length * 2, true);\n\n return this._floatTo16BitPCM(view, buffer, 44);\n }\n\n /**\n * Converts a Float32Array to 16-bit PCM.\n *\n * @internal\n */\n private _floatTo16BitPCM(dataview: DataView, buffer: Float32Array, offset: number): DataView {\n for (let i = 0; i < buffer.length; i++, offset += 2) {\n const tmp = Math.max(-1, Math.min(1, buffer[i]));\n dataview.setInt16(offset, tmp < 0 ? tmp * 0x8000 : tmp * 0x7fff, true);\n }\n\n return dataview;\n }\n\n /**\n * Writes a string to a DataView at the specified offset.\n *\n * @internal\n */\n private _writeString(dataview: DataView, offset: number, header: string): void {\n for (let i = 0; i < header.length; i++) {\n dataview.setUint8(offset + i, header.charCodeAt(i));\n }\n }\n\n /**\n * Converts an AudioBuffer to a Float32Array.\n *\n * @internal\n */\n private _interleave(input: AudioBuffer): Float32Array {\n const buffer = input.getChannelData(0),\n length = buffer.length * 2,\n result = new Float32Array(length);\n\n let index = 0,\n inputIndex = 0;\n\n while (index < length) {\n result[index++] = buffer[inputIndex];\n result[index++] = buffer[inputIndex];\n inputIndex++;\n }\n return result;\n }\n\n /**\n * Creates an HTMLAudioElement whose source is the specified Blob.\n *\n * @internal\n */\n private _renderAudioElement(blob: Blob): HTMLAudioElement {\n const audio = document.createElement('audio');\n\n audio.controls = true;\n audio.src = this._renderURL(blob);\n\n return audio;\n }\n\n /**\n * Creates an Object URL for the specified Blob.\n *\n * @internal\n */\n private _renderURL(blob: Blob): string {\n return (window.URL || window.webkitURL).createObjectURL(blob);\n }\n}\n"],"sourceRoot":""}
|
|
@@ -1,61 +1,60 @@
|
|
|
1
1
|
<!DOCTYPE html>
|
|
2
2
|
<html lang="en">
|
|
3
|
-
<head>
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
</
|
|
61
|
-
</html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>Audio from Client - Crunker Example</title>
|
|
7
|
+
<style>
|
|
8
|
+
form {
|
|
9
|
+
display: flex;
|
|
10
|
+
flex-direction: column;
|
|
11
|
+
align-items: start;
|
|
12
|
+
}
|
|
13
|
+
</style>
|
|
14
|
+
<script src="https://unpkg.com/crunker@latest/dist/crunker.js"></script>
|
|
15
|
+
</head>
|
|
16
|
+
<body>
|
|
17
|
+
<form>
|
|
18
|
+
<label>Sample rate: <input type="number" name="sampleRate" value="48000" /></label>
|
|
19
|
+
<input type="file" name="audios" multiple accept="audio/*" />
|
|
20
|
+
<div>
|
|
21
|
+
<input type="button" name="mergeBtn" value="Merge" />
|
|
22
|
+
<input type="button" name="concatBtn" value="Concat" />
|
|
23
|
+
</div>
|
|
24
|
+
</form>
|
|
25
|
+
|
|
26
|
+
<script>
|
|
27
|
+
document.querySelector('form').addEventListener('submit', (e) => e.preventDefault());
|
|
28
|
+
|
|
29
|
+
const inputSampleRate = document.querySelector('input[name=sampleRate]'),
|
|
30
|
+
inputAudios = document.querySelector('input[name=audios]');
|
|
31
|
+
|
|
32
|
+
document.querySelector('input[name=mergeBtn]').addEventListener('click', () => doTheWork('mergeAudio', 'merge'));
|
|
33
|
+
document
|
|
34
|
+
.querySelector('input[name=concatBtn]')
|
|
35
|
+
.addEventListener('click', () => doTheWork('concatAudio', 'concat'));
|
|
36
|
+
|
|
37
|
+
async function doTheWork(task, filename) {
|
|
38
|
+
const { files } = inputAudios;
|
|
39
|
+
|
|
40
|
+
if (files.length) {
|
|
41
|
+
const crunker = new Crunker({ sampleRate: inputSampleRate.value });
|
|
42
|
+
// As we aren't using `crunker.fetchAudio`, we must convert the files to buffers manually,
|
|
43
|
+
// is the same code from the source, just condensed and without need to `fetch` the files.
|
|
44
|
+
const buffers = await Promise.all(
|
|
45
|
+
Array.from(files).map(async (file) => crunker._context.decodeAudioData(await file.arrayBuffer()))
|
|
46
|
+
);
|
|
47
|
+
const merged = await crunker[task](buffers);
|
|
48
|
+
const output = await crunker.export(merged, 'audio/mp3');
|
|
49
|
+
await crunker.download(output.blob, filename);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
new Crunker().notSupported(() => {
|
|
54
|
+
window.alert('Browser unsupported!');
|
|
55
|
+
|
|
56
|
+
Array.from(document.querySelectorAll('input[type=button]')).forEach((elem) => (elem.disabled = true));
|
|
57
|
+
});
|
|
58
|
+
</script>
|
|
59
|
+
</body>
|
|
60
|
+
</html>
|
|
@@ -1,42 +1,40 @@
|
|
|
1
1
|
<!DOCTYPE html>
|
|
2
2
|
<html lang="en">
|
|
3
|
-
<head>
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
</head>
|
|
9
|
-
<body>
|
|
10
|
-
|
|
11
|
-
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>Audio from Server - Crunker Example</title>
|
|
7
|
+
<script src="https://unpkg.com/crunker@latest/dist/crunker.js"></script>
|
|
8
|
+
</head>
|
|
9
|
+
<body>
|
|
10
|
+
<button onclick="handleMerge()">Merge</button>
|
|
11
|
+
<button onclick="handleConcat()">Concat</button>
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
<script>
|
|
14
|
+
const sampleRate = 48000,
|
|
15
|
+
audioPaths = ['./1.mp3', './2.mp3'];
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
function handleMerge() {
|
|
18
|
+
doTheWork('mergeAudio', 'merge');
|
|
19
|
+
}
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
function handleConcat() {
|
|
22
|
+
doTheWork('concatAudio', 'concat');
|
|
23
|
+
}
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
25
|
+
async function doTheWork(task, filename) {
|
|
26
|
+
const crunker = new Crunker.default({ sampleRate });
|
|
27
|
+
const buffers = await crunker.fetchAudio(...audioPaths);
|
|
28
|
+
const merged = await crunker[task](buffers);
|
|
29
|
+
const output = await crunker.export(merged, 'audio/mp3');
|
|
30
|
+
await crunker.download(output.blob, filename);
|
|
31
|
+
}
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
new Crunker.default().notSupported(() => {
|
|
34
|
+
window.alert('Browser unsupported!');
|
|
35
35
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
</body>
|
|
42
|
-
</html>
|
|
36
|
+
Array.from(document.querySelectorAll('input[type=button]')).forEach((elem) => (elem.disabled = true));
|
|
37
|
+
});
|
|
38
|
+
</script>
|
|
39
|
+
</body>
|
|
40
|
+
</html>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crunker",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Simple way to merge or concatenate audio files with the Web Audio API.",
|
|
5
5
|
"main": "dist/crunker.js",
|
|
6
6
|
"types": "dist/crunker.d.ts",
|
|
@@ -56,4 +56,4 @@
|
|
|
56
56
|
"registry": "https://registry.npmjs.org"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {}
|
|
59
|
-
}
|
|
59
|
+
}
|
package/src/crunker.ts
CHANGED
|
@@ -7,7 +7,7 @@ export interface CrunkerConstructorOptions {
|
|
|
7
7
|
sampleRate: number;
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
export type CrunkerInputTypes = string | File;
|
|
10
|
+
export type CrunkerInputTypes = string | File | Blob;
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* An exported Crunker audio object.
|
|
@@ -51,7 +51,7 @@ export default class Crunker {
|
|
|
51
51
|
filepaths.map(async (filepath) => {
|
|
52
52
|
let buffer: ArrayBuffer;
|
|
53
53
|
|
|
54
|
-
if (filepath instanceof File) {
|
|
54
|
+
if (filepath instanceof File || filepath instanceof Blob) {
|
|
55
55
|
buffer = await filepath.arrayBuffer();
|
|
56
56
|
} else {
|
|
57
57
|
buffer = await fetch(filepath).then((response) => {
|