UNPKG

13.8 kBJavaScriptView Raw
1/*!
2 * wavesurfer.js 6.4.0 (2022-11-05)
3 * https://wavesurfer-js.org
4 * @license BSD-3-Clause
5 */
6(function webpackUniversalModuleDefinition(root, factory) {
7 if(typeof exports === 'object' && typeof module === 'object')
8 module.exports = factory();
9 else if(typeof define === 'function' && define.amd)
10 define("WaveSurfer", [], factory);
11 else if(typeof exports === 'object')
12 exports["WaveSurfer"] = factory();
13 else
14 root["WaveSurfer"] = root["WaveSurfer"] || {}, root["WaveSurfer"]["html-init"] = factory();
15})(self, () => {
16return /******/ (() => { // webpackBootstrap
17/******/ var __webpack_modules__ = ({
18
19/***/ "./src/html-init.js":
20/*!**************************!*\
21 !*** ./src/html-init.js ***!
22 \**************************/
23/***/ ((module, exports, __webpack_require__) => {
24
25"use strict";
26
27
28Object.defineProperty(exports, "__esModule", ({
29 value: true
30}));
31exports["default"] = void 0;
32var _loadScript = _interopRequireDefault(__webpack_require__(/*! load-script */ "./node_modules/load-script/index.js"));
33function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
35function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
36function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
37function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
38/**
39 * @typedef {Object} InitParams
40 * @property {WavesurferParams} [defaults={backend: 'MediaElement,
41 * mediaControls: true}] The default wavesurfer initialisation parameters
42 * @property {string|NodeList} containers='wavesurfer' Selector or NodeList of
43 * elements to attach instances to
44 * @property {string}
45 * pluginCdnTemplate='//localhost:8080/dist/plugin/wavesurfer.[name].js' URL
46 * template for the dynamic loading of plugins
47 * @property {function} loadPlugin If set overwrites the default request function,
48 * can be used to inject plugins differently.
49 */
50/**
51 * The HTML initialisation API is not part of the main library bundle file and
52 * must be additionally included.
53 *
54 * The API attaches wavesurfer instances to all `<wavesurfer>` (can be
55 * customised), parsing their `data-` attributes to construct an options object
56 * for initialisation. Among other things it can dynamically load plugin code.
57 *
58 * The automatic initialisation can be prevented by setting the
59 * `window.WS_StopAutoInit` flag to true. The `html-init[.min].js` file exports
60 * the `Init` class, which can be called manually.
61 *
62 * Site-wide defaults can be added by setting `window.WS_InitOptions`.
63 *
64 * @example
65 * <!-- with minimap and timeline plugin -->
66 * <wavesurfer
67 * data-url="../media/demo.wav"
68 * data-plugins="minimap,timeline"
69 * data-minimap-height="30"
70 * data-minimap-wave-color="#ddd"
71 * data-minimap-progress-color="#999"
72 * data-timeline-font-size="13px"
73 * data-timeline-container="#timeline"
74 * >
75 * </wavesurfer>
76 * <div id="timeline"></div>
77 *
78 * <!-- with regions plugin -->
79 * <wavesurfer
80 * data-url="../media/demo.wav"
81 * data-plugins="regions"
82 * data-regions-regions='[{"start": 1,"end": 3,"color": "hsla(400, 100%, 30%, 0.5)"}]'
83 * >
84 * </wavesurfer>
85 */
86var Init = /*#__PURE__*/function () {
87 /**
88 * Instantiate Init class and initialize elements
89 *
90 * This is done automatically if `window` is defined and
91 * `window.WS_StopAutoInit` is not set to true
92 *
93 * @param {WaveSurfer} WaveSurfer The WaveSurfer library object
94 * @param {InitParams} params initialisation options
95 */
96 function Init(WaveSurfer) {
97 var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
98 _classCallCheck(this, Init);
99 if (!WaveSurfer) {
100 throw new Error('WaveSurfer is not available!');
101 }
102
103 /**
104 * cache WaveSurfer
105 * @private
106 */
107 this.WaveSurfer = WaveSurfer;
108
109 /**
110 * build parameters, cache them in _params so minified builds are smaller
111 * @private
112 */
113 var _params = this.params = Object.assign({}, {
114 // wavesurfer parameter defaults so by default the audio player is
115 // usable with native media element controls
116 defaults: {
117 backend: 'MediaElement',
118 mediaControls: true
119 },
120 // containers to instantiate on, can be selector string or NodeList
121 containers: 'wavesurfer',
122 // @TODO insert plugin CDN URIs
123 pluginCdnTemplate: '//localhost:8080/dist/plugin/wavesurfer.[name].js',
124 // loadPlugin function can be overridden to inject plugin definition
125 // objects, this default function uses load-script to load a plugin
126 // and pass it to a callback
127 loadPlugin: function loadPlugin(name, cb) {
128 var src = _params.pluginCdnTemplate.replace('[name]', name);
129 (0, _loadScript.default)(src, {
130 async: false
131 }, function (err, plugin) {
132 if (err) {
133 // eslint-disable-next-line no-console
134 return console.error("WaveSurfer plugin ".concat(name, " not found at ").concat(src));
135 }
136 cb(window.WaveSurfer[name]);
137 });
138 }
139 }, params);
140 /**
141 * The nodes that should have instances attached to them
142 * @type {NodeList}
143 */
144 this.containers = typeof _params.containers == 'string' ? document.querySelectorAll(_params.containers) : _params.containers;
145 /** @private */
146 this.pluginCache = {};
147 /**
148 * An array of wavesurfer instances
149 * @type {Object[]}
150 */
151 this.instances = [];
152 this.initAllEls();
153 }
154
155 /**
156 * Initialize all container elements
157 */
158 _createClass(Init, [{
159 key: "initAllEls",
160 value: function initAllEls() {
161 var _this = this;
162 // iterate over all the container elements
163 Array.prototype.forEach.call(this.containers, function (el) {
164 // load the plugins as an array of plugin names
165 var plugins = el.dataset.plugins ? el.dataset.plugins.split(',') : [];
166
167 // no plugins to be loaded, just render
168 if (!plugins.length) {
169 return _this.initEl(el);
170 }
171 // … or: iterate over all the plugins
172 plugins.forEach(function (name, i) {
173 // plugin is not cached already, load it
174 if (!_this.pluginCache[name]) {
175 _this.params.loadPlugin(name, function (lib) {
176 _this.pluginCache[name] = lib;
177 // plugins were all loaded, render the element
178 if (i + 1 === plugins.length) {
179 _this.initEl(el, plugins);
180 }
181 });
182 } else if (i === plugins.length) {
183 // plugin was cached and this plugin was the last
184 _this.initEl(el, plugins);
185 }
186 });
187 });
188 }
189
190 /**
191 * Initialize a single container element and add to `this.instances`
192 *
193 * @param {HTMLElement} el The container to instantiate wavesurfer to
194 * @param {PluginDefinition[]} plugins An Array of plugin names to initialize with
195 * @return {Object} Wavesurfer instance
196 */
197 }, {
198 key: "initEl",
199 value: function initEl(el) {
200 var _this2 = this;
201 var plugins = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
202 var jsonRegex = /^[[|{]/;
203 // initialize plugins with the correct options
204 var initialisedPlugins = plugins.map(function (plugin) {
205 var options = {};
206 // the regex to find this plugin attributes
207 var attrNameRegex = new RegExp('^' + plugin);
208 var attrName;
209 // iterate over all the data attributes and find ones for this
210 // plugin
211 for (attrName in el.dataset) {
212 var regexResult = attrNameRegex.exec(attrName);
213 if (regexResult) {
214 var attr = el.dataset[attrName];
215 // if the string begins with a [ or a { parse it as JSON
216 var prop = jsonRegex.test(attr) ? JSON.parse(attr) : attr;
217 // this removes the plugin prefix and changes the first letter
218 // of the resulting string to lower case to follow the naming
219 // convention of ws params
220 var unprefixedOptionName = attrName.slice(plugin.length, plugin.length + 1).toLowerCase() + attrName.slice(plugin.length + 1);
221 options[unprefixedOptionName] = prop;
222 }
223 }
224 return _this2.pluginCache[plugin].create(options);
225 });
226 // build parameter object for this container
227 var params = Object.assign({
228 container: el
229 }, this.params.defaults, el.dataset, {
230 plugins: initialisedPlugins
231 });
232
233 // @TODO make nicer
234 el.style.display = 'block';
235
236 // initialize wavesurfer, load audio (with peaks if provided)
237 var instance = this.WaveSurfer.create(params);
238 var peaks = params.peaks ? JSON.parse(params.peaks) : undefined;
239 instance.load(params.url, peaks);
240
241 // push this instance into the instances cache
242 this.instances.push(instance);
243 return instance;
244 }
245 }]);
246 return Init;
247}(); // if window object exists and window.WS_StopAutoInit is not true
248if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object' && !window.WS_StopAutoInit) {
249 // call init when document is ready, apply any custom default settings
250 // in window.WS_InitOptions
251 if (document.readyState === 'complete') {
252 window.WaveSurferInit = new Init(window.WaveSurfer, window.WS_InitOptions);
253 } else {
254 window.addEventListener('load', function () {
255 window.WaveSurferInit = new Init(window.WaveSurfer, window.WS_InitOptions);
256 });
257 }
258}
259
260// export init for manual usage
261var _default = Init;
262exports["default"] = _default;
263module.exports = exports.default;
264
265/***/ }),
266
267/***/ "./node_modules/load-script/index.js":
268/*!*******************************************!*\
269 !*** ./node_modules/load-script/index.js ***!
270 \*******************************************/
271/***/ ((module) => {
272
273
274module.exports = function load (src, opts, cb) {
275 var head = document.head || document.getElementsByTagName('head')[0]
276 var script = document.createElement('script')
277
278 if (typeof opts === 'function') {
279 cb = opts
280 opts = {}
281 }
282
283 opts = opts || {}
284 cb = cb || function() {}
285
286 script.type = opts.type || 'text/javascript'
287 script.charset = opts.charset || 'utf8';
288 script.async = 'async' in opts ? !!opts.async : true
289 script.src = src
290
291 if (opts.attrs) {
292 setAttributes(script, opts.attrs)
293 }
294
295 if (opts.text) {
296 script.text = '' + opts.text
297 }
298
299 var onend = 'onload' in script ? stdOnEnd : ieOnEnd
300 onend(script, cb)
301
302 // some good legacy browsers (firefox) fail the 'in' detection above
303 // so as a fallback we always set onload
304 // old IE will ignore this and new IE will set onload
305 if (!script.onload) {
306 stdOnEnd(script, cb);
307 }
308
309 head.appendChild(script)
310}
311
312function setAttributes(script, attrs) {
313 for (var attr in attrs) {
314 script.setAttribute(attr, attrs[attr]);
315 }
316}
317
318function stdOnEnd (script, cb) {
319 script.onload = function () {
320 this.onerror = this.onload = null
321 cb(null, script)
322 }
323 script.onerror = function () {
324 // this.onload = null here is necessary
325 // because even IE9 works not like others
326 this.onerror = this.onload = null
327 cb(new Error('Failed to load ' + this.src), script)
328 }
329}
330
331function ieOnEnd (script, cb) {
332 script.onreadystatechange = function () {
333 if (this.readyState != 'complete' && this.readyState != 'loaded') return
334 this.onreadystatechange = null
335 cb(null, script) // there is no way to catch loading errors in IE8
336 }
337}
338
339
340/***/ })
341
342/******/ });
343/************************************************************************/
344/******/ // The module cache
345/******/ var __webpack_module_cache__ = {};
346/******/
347/******/ // The require function
348/******/ function __webpack_require__(moduleId) {
349/******/ // Check if module is in cache
350/******/ var cachedModule = __webpack_module_cache__[moduleId];
351/******/ if (cachedModule !== undefined) {
352/******/ return cachedModule.exports;
353/******/ }
354/******/ // Create a new module (and put it into the cache)
355/******/ var module = __webpack_module_cache__[moduleId] = {
356/******/ // no module.id needed
357/******/ // no module.loaded needed
358/******/ exports: {}
359/******/ };
360/******/
361/******/ // Execute the module function
362/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
363/******/
364/******/ // Return the exports of the module
365/******/ return module.exports;
366/******/ }
367/******/
368/************************************************************************/
369/******/
370/******/ // startup
371/******/ // Load entry module and return exports
372/******/ // This entry module is referenced by other modules so it can't be inlined
373/******/ var __webpack_exports__ = __webpack_require__("./src/html-init.js");
374/******/
375/******/ return __webpack_exports__;
376/******/ })()
377;
378});
379//# sourceMappingURL=wavesurfer-html-init.js.map
\No newline at end of file