crunker 2.0.0 → 2.1.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/.prettierignore +1 -0
- package/.yarn/install-state.gz +0 -0
- package/.yarn/releases/yarn-3.3.1.cjs +823 -0
- package/.yarnrc.yml +1 -1
- package/dist/crunker.esm.js +2 -0
- package/dist/crunker.esm.js.map +1 -0
- package/examples/client/beatBuilder.html +3 -2
- package/examples/client/index.html +3 -2
- package/examples/server/index.html +3 -2
- package/package.json +20 -18
- package/webpack.esm.config.js +16 -0
- package/.yarn/releases/yarn-3.1.1.cjs +0 -768
package/.yarnrc.yml
CHANGED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};function n(e){return function(e){if(Array.isArray(e))return r(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 r(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 r(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 r(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 a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(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)}}e.d(t,{Z:()=>i});var i=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.sampleRate;a(this,e),this._context=this._createContext(),n||(n=this._context.sampleRate),this._sampleRate=n}var t,r,i;return t=e,r=[{key:"_createContext",value:function(){return window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext,new AudioContext}},{key:"context",get:function(){return this._context}},{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,e.numberOfChannels,e.sampleRate),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,n(e.map((function(e){return e.duration}))))}},{key:"_maxNumberOfChannels",value:function(e){return Math.max.apply(Math,n(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,t,n){var r=2*t,a=2*e.length,o=36+a,i=new ArrayBuffer(8+o),u=new DataView(i);return this._writeString(u,0,"RIFF"),u.setUint32(4,o,!0),this._writeString(u,8,"WAVE"),this._writeString(u,12,"fmt "),u.setUint32(16,16,!0),u.setUint16(20,1,!0),u.setUint16(22,t,!0),u.setUint32(24,n,!0),u.setUint32(28,n*r,!0),u.setUint16(32,r,!0),u.setUint16(34,16,!0),this._writeString(u,36,"data"),u.setUint32(40,a,!0),this._floatTo16BitPCM(u,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=Array.from({length:e.numberOfChannels},(function(e,t){return t})),n=t.reduce((function(t,n){return t+e.getChannelData(n).length}),0),r=new Float32Array(n),a=0,o=0;a<n;)t.forEach((function(t){r[a++]=e.getChannelData(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)}}],r&&o(t.prototype,r),i&&o(t,i),Object.defineProperty(t,"prototype",{writable:!1}),e}(),u=t.Z;export{u as default};
|
|
2
|
+
//# sourceMappingURL=crunker.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crunker.esm.js","mappings":"AACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,I,2hCCuB7DI,EAAAA,WAUnB,aAAqE,6DAAJ,GAAnDC,EAAuD,EAAvDA,WAAuD,UACnEC,KAAKC,SAAWD,KAAKE,iBAErBH,IAAAA,EAAeC,KAAKC,SAASF,YAE7BC,KAAKG,YAAcJ,E,oDAQrB,WAEE,OADAK,OAAOC,aAAeD,OAAOC,cAAiBD,OAAeE,oBAAuBF,OAAeG,gBAC5F,IAAIF,e,mBAOb,WACE,OAAOL,KAAKC,W,wBAMdO,iBAA4E,kCAAxDC,EAAwD,yBAAxDA,EAAwD,gBAC1E,aAAaC,QAAQC,IACnBF,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AIN,GAAe,GAE3BxF,KAAKgG,iBAAiBL,EAAM7E,EAAQmF,M,8BAQ7C,SAAyBrC,EAAoB9C,EAAsB6B,GACjE,IAAK,IAAIJ,EAAI,EAAGA,EAAIzB,EAAO0B,OAAQD,IAAKI,GAAU,EAAG,CACnD,IAAMuD,EAAMlD,KAAKiC,KAAK,EAAGjC,KAAKmD,IAAI,EAAGrF,EAAOyB,KAC5CqB,EAASwC,SAASzD,EAAQuD,EAAM,EAAU,MAANA,EAAqB,MAANA,GAAc,GAGnE,OAAOtC,I,0BAQT,SAAqBA,EAAoBjB,EAAgB0D,GACvD,IAAK,IAAI9D,EAAI,EAAGA,EAAI8D,EAAO7D,OAAQD,IACjCqB,EAAS0C,SAAS3D,EAASJ,EAAG8D,EAAOE,WAAWhE,M,yBASpD,SAAoBiE,GASlB,IARA,IAAMC,EAAWC,MAAMC,KAAK,CAAEnE,OAAQgE,EAAMrE,mBAAoB,SAACyE,EAAGrE,GAAJ,OAAUA,KACpEC,EAASiE,EAAStB,QAAO,SAAC0B,EAAMC,GAAP,OAAsBD,EAAOL,EAAMnE,eAAeyE,GAAYtE,SAAQ,GAC/FuE,EAAS,IAAIC,aAAaxE,GAE5ByE,EAAQ,EACRC,EAAa,EAGVD,EAAQzE,GACbiE,EAASxE,SAAQ,SAAC6E,GAChBC,EAAOE,KAAWT,EAAMnE,eAAeyE,GAAYI,MAGrDA,IAGF,OAAOH,I,iCAQT,SAA4BhD,GAC1B,IAAMoD,EAAQ7C,SAASC,cAAc,SAKrC,OAHA4C,EAAMC,UAAW,EACjBD,EAAME,IAAMrH,KAAKiE,WAAWF,GAErBoD,I,wBAQT,SAAmBpD,GACjB,OAAQ3D,OAAOkH,KAAOlH,OAAOmH,WAAWC,gBAAgBzD,M,mFAtXvCjE,G","sources":["webpack:///webpack/bootstrap","webpack:///webpack/runtime/define property getters","webpack:///webpack/runtime/hasOwnProperty shorthand","webpack:///./crunker.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","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 * If `sampleRate` is not defined, it will auto-select an appropriate sample rate\n * for the device being used.\n */\n constructor({ sampleRate }: Partial<CrunkerConstructorOptions> = {}) {\n this._context = this._createContext();\n\n sampleRate ||= this._context.sampleRate;\n\n this._sampleRate = sampleRate;\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 *\n * The internal AudioContext used by Crunker.\n */\n get context(): AudioContext {\n return this._context;\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, buffer.numberOfChannels, buffer.sampleRate);\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, numOfChannels: number, sampleRate: number): DataView {\n const bitDepth = 16;\n const bytesPerSample = bitDepth / 8;\n const sampleSize = numOfChannels * bytesPerSample;\n\n const fileHeaderSize = 8;\n const chunkHeaderSize = 36;\n const chunkDataSize = buffer.length * bytesPerSample;\n const chunkTotalSize = chunkHeaderSize + chunkDataSize;\n\n const arrayBuffer = new ArrayBuffer(fileHeaderSize + chunkTotalSize);\n const view = new DataView(arrayBuffer);\n\n this._writeString(view, 0, 'RIFF');\n view.setUint32(4, chunkTotalSize, 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, numOfChannels, true);\n view.setUint32(24, sampleRate, true);\n view.setUint32(28, sampleRate * sampleSize, true);\n view.setUint16(32, sampleSize, true);\n view.setUint16(34, bitDepth, true);\n this._writeString(view, 36, 'data');\n view.setUint32(40, chunkDataSize, true);\n\n return this._floatTo16BitPCM(view, buffer, fileHeaderSize + chunkHeaderSize);\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 channels = Array.from({ length: input.numberOfChannels }, (_, i) => i);\n const length = channels.reduce((prev, channelIdx) => prev + input.getChannelData(channelIdx).length, 0);\n const result = new Float32Array(length);\n\n let index = 0;\n let inputIndex = 0;\n\n // for 2 channels its like: [L[0], R[0], L[1], R[1], ... , L[n], R[n]]\n while (index < length) {\n channels.forEach((channelIdx) => {\n result[index++] = input.getChannelData(channelIdx)[inputIndex];\n });\n\n inputIndex++;\n }\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"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Crunker","sampleRate","this","_context","_createContext","_sampleRate","window","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","i","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","numOfChannels","sampleSize","bitDepth","chunkDataSize","chunkTotalSize","ArrayBuffer","view","DataView","_writeString","setUint32","setUint16","_floatTo16BitPCM","fileHeaderSize","tmp","min","setInt16","header","setUint8","charCodeAt","input","channels","Array","from","_","prev","channelIdx","result","Float32Array","index","inputIndex","audio","controls","src","URL","webkitURL","createObjectURL"],"sourceRoot":""}
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<title>Crunker - Beat machine example</title>
|
|
5
|
-
<script
|
|
6
|
-
|
|
5
|
+
<script type="module">
|
|
6
|
+
import Crunker from 'https://unpkg.com/crunker@latest/dist/crunker.esm.js';
|
|
7
|
+
|
|
7
8
|
const mergeOneLine = async (crunker, buffer, times) => {
|
|
8
9
|
const audios = times.map((t) => crunker.padAudio(buffer, 0, t));
|
|
9
10
|
return crunker.mergeAudio(audios);
|
|
@@ -11,7 +11,6 @@
|
|
|
11
11
|
align-items: start;
|
|
12
12
|
}
|
|
13
13
|
</style>
|
|
14
|
-
<script src="https://unpkg.com/crunker@latest/dist/crunker.js"></script>
|
|
15
14
|
</head>
|
|
16
15
|
<body>
|
|
17
16
|
<form>
|
|
@@ -23,7 +22,9 @@
|
|
|
23
22
|
</div>
|
|
24
23
|
</form>
|
|
25
24
|
|
|
26
|
-
<script>
|
|
25
|
+
<script type="module">
|
|
26
|
+
import Crunker from 'https://unpkg.com/crunker@latest/dist/crunker.esm.js';
|
|
27
|
+
|
|
27
28
|
document.querySelector('form').addEventListener('submit', (e) => e.preventDefault());
|
|
28
29
|
|
|
29
30
|
const inputSampleRate = document.querySelector('input[name=sampleRate]'),
|
|
@@ -4,13 +4,14 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Audio from Server - Crunker Example</title>
|
|
7
|
-
<script src="https://unpkg.com/crunker@latest/dist/crunker.js"></script>
|
|
8
7
|
</head>
|
|
9
8
|
<body>
|
|
10
9
|
<button onclick="handleMerge()">Merge</button>
|
|
11
10
|
<button onclick="handleConcat()">Concat</button>
|
|
12
11
|
|
|
13
|
-
<script>
|
|
12
|
+
<script type="module">
|
|
13
|
+
import Crunker from 'https://unpkg.com/crunker@latest/dist/crunker.esm.js';
|
|
14
|
+
|
|
14
15
|
const sampleRate = 48000,
|
|
15
16
|
audioPaths = ['./1.mp3', './2.mp3'];
|
|
16
17
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crunker",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.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",
|
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
"type-check:watch": "yarn run type-check -- --watch",
|
|
14
14
|
"build": "yarn run build:prod && yarn run build:types",
|
|
15
15
|
"build:test": "webpack --config webpack.test.config.js --mode development",
|
|
16
|
-
"build:prod": "
|
|
16
|
+
"build:prod": "yarn run build:prod:cjs && yarn run build:prod:esm",
|
|
17
|
+
"build:prod:cjs": "webpack --config webpack.config.js --mode production",
|
|
18
|
+
"build:prod:esm": "webpack --config webpack.esm.config.js --mode production",
|
|
17
19
|
"build:types": "tsc --emitDeclarationOnly",
|
|
18
20
|
"prepublishOnly": "yarn run build",
|
|
19
21
|
"format": "prettier --write .",
|
|
@@ -40,26 +42,26 @@
|
|
|
40
42
|
},
|
|
41
43
|
"homepage": "https://github.com/jaggad/crunker#readme",
|
|
42
44
|
"devDependencies": {
|
|
43
|
-
"@babel/cli": "^7.
|
|
44
|
-
"@babel/core": "^7.
|
|
45
|
-
"@babel/preset-env": "^7.
|
|
46
|
-
"@babel/preset-typescript": "^7.
|
|
47
|
-
"babel-loader": "^8.
|
|
48
|
-
"babel-minify": "^0.5.
|
|
49
|
-
"chai": "^4.3.
|
|
50
|
-
"karma": "^6.
|
|
45
|
+
"@babel/cli": "^7.20.7",
|
|
46
|
+
"@babel/core": "^7.20.12",
|
|
47
|
+
"@babel/preset-env": "^7.20.2",
|
|
48
|
+
"@babel/preset-typescript": "^7.18.6",
|
|
49
|
+
"babel-loader": "^8.3.0",
|
|
50
|
+
"babel-minify": "^0.5.2",
|
|
51
|
+
"chai": "^4.3.7",
|
|
52
|
+
"karma": "^6.4.1",
|
|
51
53
|
"karma-chai": "^0.1.0",
|
|
52
|
-
"karma-chrome-launcher": "^3.1.
|
|
54
|
+
"karma-chrome-launcher": "^3.1.1",
|
|
53
55
|
"karma-mocha": "^2.0.1",
|
|
54
|
-
"mocha": "^9.2.
|
|
55
|
-
"prettier": "^2.
|
|
56
|
-
"terser-webpack-plugin": "^5.3.
|
|
57
|
-
"typescript": "^4.
|
|
58
|
-
"webpack": "^5.
|
|
59
|
-
"webpack-cli": "^
|
|
56
|
+
"mocha": "^9.2.2",
|
|
57
|
+
"prettier": "^2.8.3",
|
|
58
|
+
"terser-webpack-plugin": "^5.3.6",
|
|
59
|
+
"typescript": "^4.9.5",
|
|
60
|
+
"webpack": "^5.75.0",
|
|
61
|
+
"webpack-cli": "^5.0.1"
|
|
60
62
|
},
|
|
61
63
|
"publishConfig": {
|
|
62
64
|
"registry": "https://registry.npmjs.org"
|
|
63
65
|
},
|
|
64
|
-
"packageManager": "yarn@3.
|
|
66
|
+
"packageManager": "yarn@3.3.1"
|
|
65
67
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const config = require('./webpack.config.js');
|
|
2
|
+
|
|
3
|
+
config.experiments = {
|
|
4
|
+
outputModule: true,
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
config.output = {
|
|
8
|
+
path: __dirname + '/dist',
|
|
9
|
+
filename: 'crunker.esm.js',
|
|
10
|
+
module: true,
|
|
11
|
+
library: {
|
|
12
|
+
type: 'module',
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
module.exports = config;
|