@vunk/plus 1.12.2 → 1.13.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.
Files changed (173) hide show
  1. package/components/_plugin-vue_export-helper-BHFhmbuH.js +1 -0
  2. package/components/_plugin-vue_export-helper-CHgC5LLL.mjs +9 -0
  3. package/components/agent-chat-provider/index.cjs +1 -0
  4. package/components/agent-chat-provider/index.mjs +113 -187
  5. package/components/agent-chat-provider/src/index.vue.d.ts +3 -2
  6. package/components/avatar/index.cjs +1 -0
  7. package/components/avatar/index.mjs +25 -31
  8. package/components/avatar/src/index.vue.d.ts +40 -39
  9. package/components/broadcasting-markdown/__tests__/const.test.d.ts +1 -0
  10. package/components/broadcasting-markdown/__tests__/utils.test.d.ts +1 -0
  11. package/components/broadcasting-markdown/index.cjs +5 -0
  12. package/components/broadcasting-markdown/index.mjs +346 -4376
  13. package/components/broadcasting-markdown/src/howler-speech.vue.d.ts +18 -24
  14. package/components/broadcasting-markdown/src/index.vue.d.ts +101 -51
  15. package/components/broadcasting-markdown/src/paragraph.vue.d.ts +17 -29
  16. package/components/broadcasting-markdown/src/speech-error.vue.d.ts +2 -59
  17. package/components/bubble-list/index.cjs +1 -0
  18. package/components/bubble-list/index.mjs +220 -302
  19. package/components/bubble-list/src/core/index.vue.d.ts +40 -885
  20. package/components/bubble-list/src/core/loading.vue.d.ts +3 -0
  21. package/components/bubble-list/src/index.vue.d.ts +29 -1321
  22. package/components/bubble-templates/index.cjs +1 -0
  23. package/components/bubble-templates/index.mjs +34 -49
  24. package/components/bubble-templates/src/index.vue.d.ts +3 -224
  25. package/components/chat-independent/index.cjs +1 -0
  26. package/components/chat-independent/index.mjs +105 -212
  27. package/components/chat-independent/src/index.vue.d.ts +20 -2712
  28. package/components/components.css +1 -0
  29. package/components/drawer/index.cjs +1 -0
  30. package/components/drawer/index.mjs +53 -94
  31. package/components/drawer/src/ctx.d.ts +22 -22
  32. package/components/drawer/src/index.vue.d.ts +84 -557
  33. package/components/index.cjs +1 -0
  34. package/components/index.d.ts +1 -0
  35. package/components/lottie-animation/index.cjs +1 -0
  36. package/components/lottie-animation/index.mjs +36 -55
  37. package/components/lottie-animation/src/index.vue.d.ts +3 -2
  38. package/components/metahuman-broadcasting/index.cjs +1 -0
  39. package/components/metahuman-broadcasting/index.mjs +89 -140
  40. package/components/metahuman-broadcasting/src/index.vue.d.ts +16 -718
  41. package/components/monaco-editor/index.cjs +1 -0
  42. package/components/monaco-editor/index.mjs +68 -95
  43. package/components/monaco-editor/src/index.vue.d.ts +3 -2
  44. package/components/monaco-environment/index.cjs +1 -0
  45. package/components/monaco-environment/index.mjs +23 -38
  46. package/components/monaco-environment/src/index.vue.d.ts +2 -1
  47. package/components/pixi-frame/index.cjs +1 -0
  48. package/components/pixi-frame/index.mjs +501 -1978
  49. package/components/pixi-frame/src/apng.vue.d.ts +17 -73
  50. package/components/pixi-frame/src/bitmap-generator.vue.d.ts +24 -66
  51. package/components/pixi-frame/src/bitmap.vue.d.ts +28 -80
  52. package/components/pixi-frame/src/buffer-image.vue.d.ts +29 -97
  53. package/components/pixi-frame/src/core.vue.d.ts +20 -75
  54. package/components/pixi-frame/src/index.vue.d.ts +302 -237
  55. package/components/pixi-frame/src/provider.vue.d.ts +12 -1
  56. package/components/pixi-frame/src/video.vue.d.ts +17 -71
  57. package/components/pixi-frame/src/view.vue.d.ts +4 -16
  58. package/components/recorder-button/index.cjs +1 -0
  59. package/components/recorder-button/index.mjs +140 -269
  60. package/components/recorder-button/src/index.vue.d.ts +67 -66
  61. package/components/routes-menu-content/index.cjs +1 -0
  62. package/components/routes-menu-content/index.mjs +150 -229
  63. package/components/routes-menu-content/src/index.vue.d.ts +27 -26
  64. package/components/routes-menu-content/src/item/core/index.vue.d.ts +27 -26
  65. package/components/routes-menu-content/src/item/index.vue.d.ts +27 -26
  66. package/components/scrollbar/index.cjs +1 -0
  67. package/components/scrollbar/index.mjs +288 -567
  68. package/components/scrollbar/src/bar.vue.d.ts +6 -133
  69. package/components/scrollbar/src/index.vue.d.ts +66 -337
  70. package/components/scrollbar/src/thumb.vue.d.ts +3 -80
  71. package/components/sender/index.cjs +1 -0
  72. package/components/sender/index.mjs +156 -285
  73. package/components/sender/src/SenderHeader.vue.d.ts +14 -221
  74. package/components/sender/src/index.vue.d.ts +16 -505
  75. package/components/speech-button/index.cjs +1 -0
  76. package/components/speech-button/index.mjs +98 -144
  77. package/components/speech-button/src/LoadingIcon.vue.d.ts +2 -1
  78. package/components/speech-button/src/RecordingIcon.vue.d.ts +2 -1
  79. package/components/speech-button/src/index.vue.d.ts +6 -5
  80. package/components/table-columns/index.cjs +1 -0
  81. package/components/table-columns/index.mjs +48 -78
  82. package/components/table-columns/src/ctx.d.ts +10 -10
  83. package/components/table-columns/src/el-ctx.d.ts +1 -1
  84. package/components/table-columns/src/index.vue.d.ts +24 -23
  85. package/components/tables-v1/index.cjs +1 -0
  86. package/components/tables-v1/index.mjs +99 -160
  87. package/components/tables-v1/src/ctx.d.ts +28 -28
  88. package/components/tables-v1/src/el-ctx.d.ts +2 -2
  89. package/components/tables-v1/src/index.vue.d.ts +88 -2243
  90. package/components/tables-v1-checkbox/index.cjs +1 -0
  91. package/components/tables-v1-checkbox/index.mjs +116 -4043
  92. package/components/tables-v1-checkbox/src/ctx.d.ts +26 -26
  93. package/components/tables-v1-checkbox/src/index.vue.d.ts +176 -2330
  94. package/components/text/index.cjs +1 -0
  95. package/components/text/index.mjs +70 -108
  96. package/components/text/src/ctx.d.ts +31 -31
  97. package/components/text/src/index.vue.d.ts +92 -1819
  98. package/components/thinking/index.cjs +1 -0
  99. package/components/thinking/index.mjs +127 -227
  100. package/components/thinking/src/index.vue.d.ts +22 -2044
  101. package/components/typing-markdown/index.cjs +1 -0
  102. package/components/typing-markdown/index.mjs +61 -201
  103. package/components/typing-markdown/src/index.vue.d.ts +3 -2
  104. package/components/vditor/index.cjs +1 -0
  105. package/components/vditor/index.mjs +121 -195
  106. package/components/vditor/src/ctx.d.ts +2 -2
  107. package/components/vditor/src/handle-fullscreen.vue.d.ts +3 -2
  108. package/components/vditor/src/handle-value.vue.d.ts +3 -2
  109. package/components/vditor/src/index.vue.d.ts +5 -4
  110. package/components/xgplayer/index.cjs +1 -0
  111. package/components/xgplayer/index.mjs +49 -90
  112. package/components/xgplayer/src/core.vue.d.ts +13 -18
  113. package/components/xgplayer/src/index.vue.d.ts +13 -67
  114. package/composables/el-breakpoints/index.cjs +1 -0
  115. package/composables/el-breakpoints/index.d.ts +10 -10
  116. package/composables/el-breakpoints/index.mjs +10 -12
  117. package/composables/index.cjs +1 -0
  118. package/composables/index.d.ts +1 -0
  119. package/composables/recorder/index.cjs +1 -0
  120. package/composables/recorder/index.mjs +9172 -14803
  121. package/element/_plugin-vue_export-helper-BHFhmbuH.js +1 -0
  122. package/element/bubble/index.cjs +3 -0
  123. package/element/bubble/index.d.ts +1 -1
  124. package/element/bubble/index.mjs +1 -1
  125. package/element/bubble/src/index.vue.d.ts +22 -22
  126. package/element/index.css +1 -1
  127. package/element/thinking/index.cjs +1 -0
  128. package/element/thinking/index.d.ts +1 -1
  129. package/element/thinking/index.mjs +1 -1
  130. package/element/thinking/src/index.vue.d.ts +26 -26
  131. package/element/thinking/src/types.d.ts +10 -0
  132. package/icons/_plugin-vue_export-helper-BHFhmbuH.js +1 -0
  133. package/icons/_plugin-vue_export-helper-CHgC5LLL.mjs +9 -0
  134. package/icons/end/index.cjs +1 -0
  135. package/icons/end/index.mjs +21 -26
  136. package/icons/end/src/index.vue.d.ts +3 -0
  137. package/icons/keyboard/index.cjs +1 -0
  138. package/icons/keyboard/index.mjs +21 -26
  139. package/icons/keyboard/src/index.vue.d.ts +3 -0
  140. package/icons/start/index.cjs +1 -0
  141. package/icons/start/index.mjs +21 -26
  142. package/icons/start/src/index.vue.d.ts +3 -0
  143. package/icons/voice/index.cjs +1 -0
  144. package/icons/voice/index.mjs +26 -44
  145. package/icons/voice/src/index.vue.d.ts +2 -3
  146. package/index.css +2 -558
  147. package/index.d.ts +1 -0
  148. package/package.json +78 -87
  149. package/shared/data/index.cjs +1 -0
  150. package/shared/data/index.mjs +16 -22
  151. package/shared/types/index.cjs +1 -0
  152. package/shared/types/index.d.ts +1 -0
  153. package/components/LinkOutlined.mjs +0 -1321
  154. package/components/_commonjsHelpers.mjs +0 -7
  155. package/components/_plugin-vue_export-helper.mjs +0 -9
  156. package/components/bubble-list/index.css +0 -70
  157. package/components/bubble-templates/index.css +0 -4
  158. package/components/chat-independent/index.css +0 -47
  159. package/components/drawer/index.css +0 -124
  160. package/components/index2.mjs +0 -78
  161. package/components/lottie-animation/index.css +0 -4
  162. package/components/monaco-editor/index.css +0 -4
  163. package/components/pixi-frame/index.css +0 -4
  164. package/components/recorder-button/index.css +0 -69
  165. package/components/sender/index.css +0 -22
  166. package/components/speech-button/index.css +0 -10
  167. package/components/tables-v1/index.css +0 -7
  168. package/components/tables-v1-checkbox/index.css +0 -8
  169. package/components/thinking/index.css +0 -125
  170. package/components/typing-markdown/index.css +0 -31
  171. package/components/vditor/index.css +0 -12
  172. package/components/xgplayer/index.css +0 -1
  173. package/icons/_plugin-vue_export-helper.mjs +0 -9
@@ -1,169 +1,30 @@
1
- import { VkTypingMarkdown } from '@vunk/plus/components/typing-markdown';
2
- import { setData } from '@vunk/core';
3
- import { useDeferred, useDataComputed } from '@vunk/core/composables';
4
- import { blobToDataURL } from '@vunk/shared/data/blob';
5
- import { TickerStatus } from '@vunk/shared/enum';
6
- import { shallowRef, computed, watch, onBeforeUnmount, watchEffect, defineComponent, onMounted, renderSlot, nextTick, createCommentVNode, ref, resolveComponent, openBlock, createElementBlock, Fragment, createVNode, renderList, createBlock, withCtx } from 'vue';
7
- import { noop } from '@vunk/shared/function';
8
- import { c as commonjsGlobal } from '../_commonjsHelpers.mjs';
9
- import { _ as _export_sfc } from '../_plugin-vue_export-helper.mjs';
10
- import { Deferred } from '@vunk/shared/promise';
11
-
12
- var __defProp = Object.defineProperty;
13
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
16
-
17
- // src/lib/_AsyncQueueEntry.ts
18
- var _AsyncQueueEntry = class _AsyncQueueEntry {
19
- constructor(queue) {
20
- __publicField(this, "promise");
21
- __publicField(this, "resolve");
22
- __publicField(this, "reject");
23
- __publicField(this, "queue");
24
- __publicField(this, "signal", null);
25
- __publicField(this, "signalListener", null);
26
- this.queue = queue;
27
- this.promise = new Promise((resolve, reject) => {
28
- this.resolve = resolve;
29
- this.reject = reject;
30
- });
31
- }
32
- setSignal(signal) {
33
- if (signal.aborted) return this;
34
- this.signal = signal;
35
- this.signalListener = () => {
36
- const index = this.queue["promises"].indexOf(this);
37
- if (index !== -1) this.queue["promises"].splice(index, 1);
38
- this.reject(new Error("Request aborted manually"));
39
- };
40
- this.signal.addEventListener("abort", this.signalListener);
41
- return this;
42
- }
43
- use() {
44
- this.dispose();
45
- this.resolve();
46
- return this;
47
- }
48
- abort() {
49
- this.dispose();
50
- this.reject(new Error("Request aborted manually"));
51
- return this;
52
- }
53
- dispose() {
54
- if (this.signal) {
55
- this.signal.removeEventListener("abort", this.signalListener);
56
- this.signal = null;
57
- this.signalListener = null;
58
- }
59
- }
60
- };
61
- __name(_AsyncQueueEntry, "AsyncQueueEntry");
62
- var AsyncQueueEntry = _AsyncQueueEntry;
63
-
64
- // src/lib/AsyncQueue.ts
65
- var _AsyncQueue = class _AsyncQueue {
66
- constructor() {
67
- /**
68
- * The promises array
69
- */
70
- __publicField(this, "promises", []);
71
- }
72
- /**
73
- * The amount of entries in the queue, including the head.
74
- * @seealso {@link queued} for the queued count.
75
- */
76
- get remaining() {
77
- return this.promises.length;
78
- }
79
- /**
80
- * The amount of queued entries.
81
- * @seealso {@link remaining} for the count with the head.
82
- */
83
- get queued() {
84
- return this.remaining === 0 ? 0 : this.remaining - 1;
85
- }
86
- /**
87
- * Waits for last promise and queues a new one
88
- * @example
89
- * ```typescript
90
- * const queue = new AsyncQueue();
91
- * async function request(url, options) {
92
- * await queue.wait({ signal: options.signal });
93
- * try {
94
- * const result = await fetch(url, options);
95
- * // Do some operations with 'result'
96
- * } finally {
97
- * // Remove first entry from the queue and resolve for the next entry
98
- * queue.shift();
99
- * }
100
- * }
101
- *
102
- * request(someUrl1, someOptions1); // Will call fetch() immediately
103
- * request(someUrl2, someOptions2); // Will call fetch() after the first finished
104
- * request(someUrl3, someOptions3); // Will call fetch() after the second finished
105
- * ```
106
- */
107
- wait(options) {
108
- const entry = new AsyncQueueEntry(this);
109
- if (this.promises.length === 0) {
110
- this.promises.push(entry);
111
- return Promise.resolve();
112
- }
113
- this.promises.push(entry);
114
- if (options?.signal) entry.setSignal(options.signal);
115
- return entry.promise;
116
- }
117
- /**
118
- * Unlocks the head lock and transfers the next lock (if any) to the head.
119
- */
120
- shift() {
121
- if (this.promises.length === 0) return;
122
- if (this.promises.length === 1) {
123
- this.promises.shift();
124
- return;
125
- }
126
- this.promises.shift();
127
- this.promises[0].use();
128
- }
129
- /**
130
- * Aborts all the pending promises.
131
- * @note To avoid race conditions, this does **not** unlock the head lock.
132
- */
133
- abortAll() {
134
- if (this.queued === 0) return;
135
- for (let i = 1; i < this.promises.length; ++i) {
136
- this.promises[i].abort();
137
- }
138
- this.promises.length = 1;
139
- }
140
- };
141
- __name(_AsyncQueue, "AsyncQueue");
142
- var AsyncQueue = _AsyncQueue;
143
-
144
- function markdownToPlainText(md) {
145
- return md.replace(/!\[.*?\]\(.*?\)/g, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^#{1,6}\s+/gm, "").replace(/\*\*(.*?)\*\*/g, "$1").replace(/__(.*?)__/g, "$1").replace(/\*(.*?)\*/g, "$1").replace(/_(.*?)_/g, "$1").replace(/`(.*?)`/g, "$1").replace(/```[\s\S]*?```/g, "").replace(/\n{2,}/g, "\n").replace(/-{3,}/g, "").replace(/^\s*-\s+/gm, "").replace(/\|/g, "").trim();
1
+ import { AsyncQueue as U } from "@sapphire/async-queue";
2
+ import { VkTypingMarkdown as R } from "@vunk/plus/components/typing-markdown";
3
+ import { setData as I } from "@vunk/core";
4
+ import { useDeferred as q, useDataComputed as z } from "@vunk/core/composables";
5
+ import { blobToDataURL as J } from "@vunk/shared/data/blob";
6
+ import { TickerStatus as m } from "@vunk/shared/enum";
7
+ import { shallowRef as F, computed as w, watch as _, onBeforeUnmount as W, watchEffect as Q, defineComponent as B, onMounted as x, renderSlot as S, nextTick as G, createCommentVNode as K, ref as X, resolveComponent as T, createElementBlock as D, openBlock as $, Fragment as j, createVNode as A, renderList as Y, createBlock as Z, withCtx as ee } from "vue";
8
+ import { noop as L } from "@vunk/shared/function";
9
+ import { Howl as M } from "howler";
10
+ import { Deferred as te } from "@vunk/shared/promise";
11
+ import { consola as ae } from "consola";
12
+ import { _ as re } from "../_plugin-vue_export-helper-CHgC5LLL.mjs";
13
+ function ne(e) {
14
+ return e.replace(/!\[.*?\]\(.*?\)/g, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^#{1,6}\s+/gm, "").replace(/\*\*(.*?)\*\*/g, "$1").replace(/__(.*?)__/g, "$1").replace(/\*(.*?)\*/g, "$1").replace(/_(.*?)_/g, "$1").replace(/`(.*?)`/g, "$1").replace(/```[\s\S]*?```/g, "").replace(/\n{2,}/g, `
15
+ `).replace(/-{3,}/g, "").replace(/^\s*-\s+/gm, "").replace(/\|/g, "").trim();
146
16
  }
147
- function defaultRender(mdText) {
148
- return markdownToPlainText(mdText);
17
+ function C(e) {
18
+ return ne(e);
149
19
  }
150
- var ParagraphStatus = /* @__PURE__ */ ((ParagraphStatus2) => {
151
- ParagraphStatus2["initial"] = "initial";
152
- ParagraphStatus2["processing"] = "processing";
153
- ParagraphStatus2["pending"] = "pending";
154
- ParagraphStatus2["fulfilled"] = "fulfilled";
155
- ParagraphStatus2["rejected"] = "rejected";
156
- return ParagraphStatus2;
157
- })(ParagraphStatus || {});
158
- const Broadcast = TickerStatus;
159
-
160
- const props = {
20
+ var i = /* @__PURE__ */ ((e) => (e.initial = "initial", e.processing = "processing", e.pending = "pending", e.fulfilled = "fulfilled", e.rejected = "rejected", e))(i || {});
21
+ const y = m, H = {
161
22
  /**
162
23
  * @description md文本转纯文本的函数
163
24
  */
164
25
  render: {
165
26
  type: Function,
166
- default: defaultRender
27
+ default: C
167
28
  },
168
29
  /**
169
30
  * @description 段落详情
@@ -183,3414 +44,134 @@ const props = {
183
44
  * @description 游标阅读延迟
184
45
  */
185
46
  delay: {
186
- type: Number,
187
- default: 0
188
- },
189
- /**
190
- * @description 段落切割符号
191
- */
192
- separators: {
193
- type: Array,
194
- default: () => ["\n\n", "\n"]
195
- },
196
- /**
197
- * @description 组件内会根据当前游标是否和 source 长度一致来判断,是否持续阅读, 当一致时,会关闭阅读状态。但若设置为 true,则会持续阅读, 这在动态接收数据时会有用
198
- */
199
- keepRead: {
200
- type: Boolean,
201
- default: false
202
- },
203
- /**
204
- * @description 是否使用自定义语音合成
205
- */
206
- textToSpeech: {
207
- type: Function,
208
- default: void 0
209
- },
210
- /**
211
- * @description 段落处理函数
212
- */
213
- processing: {
214
- type: Function,
215
- default: noop
216
- },
217
- status: {
218
- type: String,
219
- default: TickerStatus.pending
220
- },
221
- paragraphMinlength: {
222
- type: Number,
223
- default: 20
224
- },
225
- /**
226
- * @description 禁用, 即不产出段落
227
- */
228
- disabled: {
229
- type: Boolean,
230
- default: false
231
- }
232
- };
233
- const emits = {
234
- "setData": (e) => e,
235
- "update:status": (_) => true,
236
- "paragraphLoad": (_) => true,
237
- "complete": () => true
238
- };
239
- const paragraphProps = {
240
- data: {
241
- type: Object,
242
- default: () => ({})
243
- },
244
- deferred: {
245
- type: Object,
246
- required: true
247
- },
248
- render: {
249
- type: Function,
250
- default: defaultRender
251
- }
252
- };
253
- const paragraphEmits = {
254
- setData: (e) => e,
255
- load: (_) => true
256
- };
257
-
258
- var ctx = /*#__PURE__*/Object.freeze({
259
- __proto__: null,
260
- emits: emits,
261
- paragraphEmits: paragraphEmits,
262
- paragraphProps: paragraphProps,
263
- props: props
264
- });
265
-
266
- var howler = {};
267
-
268
- /*!
269
- * howler.js v2.2.4
270
- * howlerjs.com
271
- *
272
- * (c) 2013-2020, James Simpson of GoldFire Studios
273
- * goldfirestudios.com
274
- *
275
- * MIT License
276
- */
277
-
278
- (function (exports) {
279
- (function() {
280
-
281
- /** Global Methods **/
282
- /***************************************************************************/
283
-
284
- /**
285
- * Create the global controller. All contained methods and properties apply
286
- * to all sounds that are currently playing or will be in the future.
287
- */
288
- var HowlerGlobal = function() {
289
- this.init();
290
- };
291
- HowlerGlobal.prototype = {
292
- /**
293
- * Initialize the global Howler object.
294
- * @return {Howler}
295
- */
296
- init: function() {
297
- var self = this || Howler;
298
-
299
- // Create a global ID counter.
300
- self._counter = 1000;
301
-
302
- // Pool of unlocked HTML5 Audio objects.
303
- self._html5AudioPool = [];
304
- self.html5PoolSize = 10;
305
-
306
- // Internal properties.
307
- self._codecs = {};
308
- self._howls = [];
309
- self._muted = false;
310
- self._volume = 1;
311
- self._canPlayEvent = 'canplaythrough';
312
- self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null;
313
-
314
- // Public properties.
315
- self.masterGain = null;
316
- self.noAudio = false;
317
- self.usingWebAudio = true;
318
- self.autoSuspend = true;
319
- self.ctx = null;
320
-
321
- // Set to false to disable the auto audio unlocker.
322
- self.autoUnlock = true;
323
-
324
- // Setup the various state values for global tracking.
325
- self._setup();
326
-
327
- return self;
328
- },
329
-
330
- /**
331
- * Get/set the global volume for all sounds.
332
- * @param {Float} vol Volume from 0.0 to 1.0.
333
- * @return {Howler/Float} Returns self or current volume.
334
- */
335
- volume: function(vol) {
336
- var self = this || Howler;
337
- vol = parseFloat(vol);
338
-
339
- // If we don't have an AudioContext created yet, run the setup.
340
- if (!self.ctx) {
341
- setupAudioContext();
342
- }
343
-
344
- if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
345
- self._volume = vol;
346
-
347
- // Don't update any of the nodes if we are muted.
348
- if (self._muted) {
349
- return self;
350
- }
351
-
352
- // When using Web Audio, we just need to adjust the master gain.
353
- if (self.usingWebAudio) {
354
- self.masterGain.gain.setValueAtTime(vol, Howler.ctx.currentTime);
355
- }
356
-
357
- // Loop through and change volume for all HTML5 audio nodes.
358
- for (var i=0; i<self._howls.length; i++) {
359
- if (!self._howls[i]._webAudio) {
360
- // Get all of the sounds in this Howl group.
361
- var ids = self._howls[i]._getSoundIds();
362
-
363
- // Loop through all sounds and change the volumes.
364
- for (var j=0; j<ids.length; j++) {
365
- var sound = self._howls[i]._soundById(ids[j]);
366
-
367
- if (sound && sound._node) {
368
- sound._node.volume = sound._volume * vol;
369
- }
370
- }
371
- }
372
- }
373
-
374
- return self;
375
- }
376
-
377
- return self._volume;
378
- },
379
-
380
- /**
381
- * Handle muting and unmuting globally.
382
- * @param {Boolean} muted Is muted or not.
383
- */
384
- mute: function(muted) {
385
- var self = this || Howler;
386
-
387
- // If we don't have an AudioContext created yet, run the setup.
388
- if (!self.ctx) {
389
- setupAudioContext();
390
- }
391
-
392
- self._muted = muted;
393
-
394
- // With Web Audio, we just need to mute the master gain.
395
- if (self.usingWebAudio) {
396
- self.masterGain.gain.setValueAtTime(muted ? 0 : self._volume, Howler.ctx.currentTime);
397
- }
398
-
399
- // Loop through and mute all HTML5 Audio nodes.
400
- for (var i=0; i<self._howls.length; i++) {
401
- if (!self._howls[i]._webAudio) {
402
- // Get all of the sounds in this Howl group.
403
- var ids = self._howls[i]._getSoundIds();
404
-
405
- // Loop through all sounds and mark the audio node as muted.
406
- for (var j=0; j<ids.length; j++) {
407
- var sound = self._howls[i]._soundById(ids[j]);
408
-
409
- if (sound && sound._node) {
410
- sound._node.muted = (muted) ? true : sound._muted;
411
- }
412
- }
413
- }
414
- }
415
-
416
- return self;
417
- },
418
-
419
- /**
420
- * Handle stopping all sounds globally.
421
- */
422
- stop: function() {
423
- var self = this || Howler;
424
-
425
- // Loop through all Howls and stop them.
426
- for (var i=0; i<self._howls.length; i++) {
427
- self._howls[i].stop();
428
- }
429
-
430
- return self;
431
- },
432
-
433
- /**
434
- * Unload and destroy all currently loaded Howl objects.
435
- * @return {Howler}
436
- */
437
- unload: function() {
438
- var self = this || Howler;
439
-
440
- for (var i=self._howls.length-1; i>=0; i--) {
441
- self._howls[i].unload();
442
- }
443
-
444
- // Create a new AudioContext to make sure it is fully reset.
445
- if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') {
446
- self.ctx.close();
447
- self.ctx = null;
448
- setupAudioContext();
449
- }
450
-
451
- return self;
452
- },
453
-
454
- /**
455
- * Check for codec support of specific extension.
456
- * @param {String} ext Audio file extention.
457
- * @return {Boolean}
458
- */
459
- codecs: function(ext) {
460
- return (this || Howler)._codecs[ext.replace(/^x-/, '')];
461
- },
462
-
463
- /**
464
- * Setup various state values for global tracking.
465
- * @return {Howler}
466
- */
467
- _setup: function() {
468
- var self = this || Howler;
469
-
470
- // Keeps track of the suspend/resume state of the AudioContext.
471
- self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended';
472
-
473
- // Automatically begin the 30-second suspend process
474
- self._autoSuspend();
475
-
476
- // Check if audio is available.
477
- if (!self.usingWebAudio) {
478
- // No audio is available on this system if noAudio is set to true.
479
- if (typeof Audio !== 'undefined') {
480
- try {
481
- var test = new Audio();
482
-
483
- // Check if the canplaythrough event is available.
484
- if (typeof test.oncanplaythrough === 'undefined') {
485
- self._canPlayEvent = 'canplay';
486
- }
487
- } catch(e) {
488
- self.noAudio = true;
489
- }
490
- } else {
491
- self.noAudio = true;
492
- }
493
- }
494
-
495
- // Test to make sure audio isn't disabled in Internet Explorer.
496
- try {
497
- var test = new Audio();
498
- if (test.muted) {
499
- self.noAudio = true;
500
- }
501
- } catch (e) {}
502
-
503
- // Check for supported codecs.
504
- if (!self.noAudio) {
505
- self._setupCodecs();
506
- }
507
-
508
- return self;
509
- },
510
-
511
- /**
512
- * Check for browser support for various codecs and cache the results.
513
- * @return {Howler}
514
- */
515
- _setupCodecs: function() {
516
- var self = this || Howler;
517
- var audioTest = null;
518
-
519
- // Must wrap in a try/catch because IE11 in server mode throws an error.
520
- try {
521
- audioTest = (typeof Audio !== 'undefined') ? new Audio() : null;
522
- } catch (err) {
523
- return self;
524
- }
525
-
526
- if (!audioTest || typeof audioTest.canPlayType !== 'function') {
527
- return self;
528
- }
529
-
530
- var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
531
-
532
- // Opera version <33 has mixed MP3 support, so we need to check for and block it.
533
- var ua = self._navigator ? self._navigator.userAgent : '';
534
- var checkOpera = ua.match(/OPR\/(\d+)/g);
535
- var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33);
536
- var checkSafari = ua.indexOf('Safari') !== -1 && ua.indexOf('Chrome') === -1;
537
- var safariVersion = ua.match(/Version\/(.*?) /);
538
- var isOldSafari = (checkSafari && safariVersion && parseInt(safariVersion[1], 10) < 15);
539
-
540
- self._codecs = {
541
- mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))),
542
- mpeg: !!mpegTest,
543
- opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''),
544
- ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
545
- oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
546
- wav: !!(audioTest.canPlayType('audio/wav; codecs="1"') || audioTest.canPlayType('audio/wav')).replace(/^no$/, ''),
547
- aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
548
- caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''),
549
- m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
550
- m4b: !!(audioTest.canPlayType('audio/x-m4b;') || audioTest.canPlayType('audio/m4b;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
551
- mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
552
- weba: !!(!isOldSafari && audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')),
553
- webm: !!(!isOldSafari && audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')),
554
- dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''),
555
- flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '')
556
- };
557
-
558
- return self;
559
- },
560
-
561
- /**
562
- * Some browsers/devices will only allow audio to be played after a user interaction.
563
- * Attempt to automatically unlock audio on the first user interaction.
564
- * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
565
- * @return {Howler}
566
- */
567
- _unlockAudio: function() {
568
- var self = this || Howler;
569
-
570
- // Only run this if Web Audio is supported and it hasn't already been unlocked.
571
- if (self._audioUnlocked || !self.ctx) {
572
- return;
573
- }
574
-
575
- self._audioUnlocked = false;
576
- self.autoUnlock = false;
577
-
578
- // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views.
579
- // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000.
580
- // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate.
581
- if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) {
582
- self._mobileUnloaded = true;
583
- self.unload();
584
- }
585
-
586
- // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per:
587
- // http://stackoverflow.com/questions/24119684
588
- self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050);
589
-
590
- // Call this method on touch start to create and play a buffer,
591
- // then check if the audio actually played to determine if
592
- // audio has now been unlocked on iOS, Android, etc.
593
- var unlock = function(e) {
594
- // Create a pool of unlocked HTML5 Audio objects that can
595
- // be used for playing sounds without user interaction. HTML5
596
- // Audio objects must be individually unlocked, as opposed
597
- // to the WebAudio API which only needs a single activation.
598
- // This must occur before WebAudio setup or the source.onended
599
- // event will not fire.
600
- while (self._html5AudioPool.length < self.html5PoolSize) {
601
- try {
602
- var audioNode = new Audio();
603
-
604
- // Mark this Audio object as unlocked to ensure it can get returned
605
- // to the unlocked pool when released.
606
- audioNode._unlocked = true;
607
-
608
- // Add the audio node to the pool.
609
- self._releaseHtml5Audio(audioNode);
610
- } catch (e) {
611
- self.noAudio = true;
612
- break;
613
- }
614
- }
615
-
616
- // Loop through any assigned audio nodes and unlock them.
617
- for (var i=0; i<self._howls.length; i++) {
618
- if (!self._howls[i]._webAudio) {
619
- // Get all of the sounds in this Howl group.
620
- var ids = self._howls[i]._getSoundIds();
621
-
622
- // Loop through all sounds and unlock the audio nodes.
623
- for (var j=0; j<ids.length; j++) {
624
- var sound = self._howls[i]._soundById(ids[j]);
625
-
626
- if (sound && sound._node && !sound._node._unlocked) {
627
- sound._node._unlocked = true;
628
- sound._node.load();
629
- }
630
- }
631
- }
632
- }
633
-
634
- // Fix Android can not play in suspend state.
635
- self._autoResume();
636
-
637
- // Create an empty buffer.
638
- var source = self.ctx.createBufferSource();
639
- source.buffer = self._scratchBuffer;
640
- source.connect(self.ctx.destination);
641
-
642
- // Play the empty buffer.
643
- if (typeof source.start === 'undefined') {
644
- source.noteOn(0);
645
- } else {
646
- source.start(0);
647
- }
648
-
649
- // Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
650
- if (typeof self.ctx.resume === 'function') {
651
- self.ctx.resume();
652
- }
653
-
654
- // Setup a timeout to check that we are unlocked on the next event loop.
655
- source.onended = function() {
656
- source.disconnect(0);
657
-
658
- // Update the unlocked state and prevent this check from happening again.
659
- self._audioUnlocked = true;
660
-
661
- // Remove the touch start listener.
662
- document.removeEventListener('touchstart', unlock, true);
663
- document.removeEventListener('touchend', unlock, true);
664
- document.removeEventListener('click', unlock, true);
665
- document.removeEventListener('keydown', unlock, true);
666
-
667
- // Let all sounds know that audio has been unlocked.
668
- for (var i=0; i<self._howls.length; i++) {
669
- self._howls[i]._emit('unlock');
670
- }
671
- };
672
- };
673
-
674
- // Setup a touch start listener to attempt an unlock in.
675
- document.addEventListener('touchstart', unlock, true);
676
- document.addEventListener('touchend', unlock, true);
677
- document.addEventListener('click', unlock, true);
678
- document.addEventListener('keydown', unlock, true);
679
-
680
- return self;
681
- },
682
-
683
- /**
684
- * Get an unlocked HTML5 Audio object from the pool. If none are left,
685
- * return a new Audio object and throw a warning.
686
- * @return {Audio} HTML5 Audio object.
687
- */
688
- _obtainHtml5Audio: function() {
689
- var self = this || Howler;
690
-
691
- // Return the next object from the pool if one exists.
692
- if (self._html5AudioPool.length) {
693
- return self._html5AudioPool.pop();
694
- }
695
-
696
- //.Check if the audio is locked and throw a warning.
697
- var testPlay = new Audio().play();
698
- if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) {
699
- testPlay.catch(function() {
700
- console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.');
701
- });
702
- }
703
-
704
- return new Audio();
705
- },
706
-
707
- /**
708
- * Return an activated HTML5 Audio object to the pool.
709
- * @return {Howler}
710
- */
711
- _releaseHtml5Audio: function(audio) {
712
- var self = this || Howler;
713
-
714
- // Don't add audio to the pool if we don't know if it has been unlocked.
715
- if (audio._unlocked) {
716
- self._html5AudioPool.push(audio);
717
- }
718
-
719
- return self;
720
- },
721
-
722
- /**
723
- * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
724
- * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
725
- * @return {Howler}
726
- */
727
- _autoSuspend: function() {
728
- var self = this;
729
-
730
- if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) {
731
- return;
732
- }
733
-
734
- // Check if any sounds are playing.
735
- for (var i=0; i<self._howls.length; i++) {
736
- if (self._howls[i]._webAudio) {
737
- for (var j=0; j<self._howls[i]._sounds.length; j++) {
738
- if (!self._howls[i]._sounds[j]._paused) {
739
- return self;
740
- }
741
- }
742
- }
743
- }
744
-
745
- if (self._suspendTimer) {
746
- clearTimeout(self._suspendTimer);
747
- }
748
-
749
- // If no sound has played after 30 seconds, suspend the context.
750
- self._suspendTimer = setTimeout(function() {
751
- if (!self.autoSuspend) {
752
- return;
753
- }
754
-
755
- self._suspendTimer = null;
756
- self.state = 'suspending';
757
-
758
- // Handle updating the state of the audio context after suspending.
759
- var handleSuspension = function() {
760
- self.state = 'suspended';
761
-
762
- if (self._resumeAfterSuspend) {
763
- delete self._resumeAfterSuspend;
764
- self._autoResume();
765
- }
766
- };
767
-
768
- // Either the state gets suspended or it is interrupted.
769
- // Either way, we need to update the state to suspended.
770
- self.ctx.suspend().then(handleSuspension, handleSuspension);
771
- }, 30000);
772
-
773
- return self;
774
- },
775
-
776
- /**
777
- * Automatically resume the Web Audio AudioContext when a new sound is played.
778
- * @return {Howler}
779
- */
780
- _autoResume: function() {
781
- var self = this;
782
-
783
- if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) {
784
- return;
785
- }
786
-
787
- if (self.state === 'running' && self.ctx.state !== 'interrupted' && self._suspendTimer) {
788
- clearTimeout(self._suspendTimer);
789
- self._suspendTimer = null;
790
- } else if (self.state === 'suspended' || self.state === 'running' && self.ctx.state === 'interrupted') {
791
- self.ctx.resume().then(function() {
792
- self.state = 'running';
793
-
794
- // Emit to all Howls that the audio has resumed.
795
- for (var i=0; i<self._howls.length; i++) {
796
- self._howls[i]._emit('resume');
797
- }
798
- });
799
-
800
- if (self._suspendTimer) {
801
- clearTimeout(self._suspendTimer);
802
- self._suspendTimer = null;
803
- }
804
- } else if (self.state === 'suspending') {
805
- self._resumeAfterSuspend = true;
806
- }
807
-
808
- return self;
809
- }
810
- };
811
-
812
- // Setup the global audio controller.
813
- var Howler = new HowlerGlobal();
814
-
815
- /** Group Methods **/
816
- /***************************************************************************/
817
-
818
- /**
819
- * Create an audio group controller.
820
- * @param {Object} o Passed in properties for this group.
821
- */
822
- var Howl = function(o) {
823
- var self = this;
824
-
825
- // Throw an error if no source is provided.
826
- if (!o.src || o.src.length === 0) {
827
- console.error('An array of source files must be passed with any new Howl.');
828
- return;
829
- }
830
-
831
- self.init(o);
832
- };
833
- Howl.prototype = {
834
- /**
835
- * Initialize a new Howl group object.
836
- * @param {Object} o Passed in properties for this group.
837
- * @return {Howl}
838
- */
839
- init: function(o) {
840
- var self = this;
841
-
842
- // If we don't have an AudioContext created yet, run the setup.
843
- if (!Howler.ctx) {
844
- setupAudioContext();
845
- }
846
-
847
- // Setup user-defined default properties.
848
- self._autoplay = o.autoplay || false;
849
- self._format = (typeof o.format !== 'string') ? o.format : [o.format];
850
- self._html5 = o.html5 || false;
851
- self._muted = o.mute || false;
852
- self._loop = o.loop || false;
853
- self._pool = o.pool || 5;
854
- self._preload = (typeof o.preload === 'boolean' || o.preload === 'metadata') ? o.preload : true;
855
- self._rate = o.rate || 1;
856
- self._sprite = o.sprite || {};
857
- self._src = (typeof o.src !== 'string') ? o.src : [o.src];
858
- self._volume = o.volume !== undefined ? o.volume : 1;
859
- self._xhr = {
860
- method: o.xhr && o.xhr.method ? o.xhr.method : 'GET',
861
- headers: o.xhr && o.xhr.headers ? o.xhr.headers : null,
862
- withCredentials: o.xhr && o.xhr.withCredentials ? o.xhr.withCredentials : false,
863
- };
864
-
865
- // Setup all other default properties.
866
- self._duration = 0;
867
- self._state = 'unloaded';
868
- self._sounds = [];
869
- self._endTimers = {};
870
- self._queue = [];
871
- self._playLock = false;
872
-
873
- // Setup event listeners.
874
- self._onend = o.onend ? [{fn: o.onend}] : [];
875
- self._onfade = o.onfade ? [{fn: o.onfade}] : [];
876
- self._onload = o.onload ? [{fn: o.onload}] : [];
877
- self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : [];
878
- self._onplayerror = o.onplayerror ? [{fn: o.onplayerror}] : [];
879
- self._onpause = o.onpause ? [{fn: o.onpause}] : [];
880
- self._onplay = o.onplay ? [{fn: o.onplay}] : [];
881
- self._onstop = o.onstop ? [{fn: o.onstop}] : [];
882
- self._onmute = o.onmute ? [{fn: o.onmute}] : [];
883
- self._onvolume = o.onvolume ? [{fn: o.onvolume}] : [];
884
- self._onrate = o.onrate ? [{fn: o.onrate}] : [];
885
- self._onseek = o.onseek ? [{fn: o.onseek}] : [];
886
- self._onunlock = o.onunlock ? [{fn: o.onunlock}] : [];
887
- self._onresume = [];
888
-
889
- // Web Audio or HTML5 Audio?
890
- self._webAudio = Howler.usingWebAudio && !self._html5;
891
-
892
- // Automatically try to enable audio.
893
- if (typeof Howler.ctx !== 'undefined' && Howler.ctx && Howler.autoUnlock) {
894
- Howler._unlockAudio();
895
- }
896
-
897
- // Keep track of this Howl group in the global controller.
898
- Howler._howls.push(self);
899
-
900
- // If they selected autoplay, add a play event to the load queue.
901
- if (self._autoplay) {
902
- self._queue.push({
903
- event: 'play',
904
- action: function() {
905
- self.play();
906
- }
907
- });
908
- }
909
-
910
- // Load the source file unless otherwise specified.
911
- if (self._preload && self._preload !== 'none') {
912
- self.load();
913
- }
914
-
915
- return self;
916
- },
917
-
918
- /**
919
- * Load the audio file.
920
- * @return {Howler}
921
- */
922
- load: function() {
923
- var self = this;
924
- var url = null;
925
-
926
- // If no audio is available, quit immediately.
927
- if (Howler.noAudio) {
928
- self._emit('loaderror', null, 'No audio support.');
929
- return;
930
- }
931
-
932
- // Make sure our source is in an array.
933
- if (typeof self._src === 'string') {
934
- self._src = [self._src];
935
- }
936
-
937
- // Loop through the sources and pick the first one that is compatible.
938
- for (var i=0; i<self._src.length; i++) {
939
- var ext, str;
940
-
941
- if (self._format && self._format[i]) {
942
- // If an extension was specified, use that instead.
943
- ext = self._format[i];
944
- } else {
945
- // Make sure the source is a string.
946
- str = self._src[i];
947
- if (typeof str !== 'string') {
948
- self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.');
949
- continue;
950
- }
951
-
952
- // Extract the file extension from the URL or base64 data URI.
953
- ext = /^data:audio\/([^;,]+);/i.exec(str);
954
- if (!ext) {
955
- ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]);
956
- }
957
-
958
- if (ext) {
959
- ext = ext[1].toLowerCase();
960
- }
961
- }
962
-
963
- // Log a warning if no extension was found.
964
- if (!ext) {
965
- console.warn('No file extension was found. Consider using the "format" property or specify an extension.');
966
- }
967
-
968
- // Check if this extension is available.
969
- if (ext && Howler.codecs(ext)) {
970
- url = self._src[i];
971
- break;
972
- }
973
- }
974
-
975
- if (!url) {
976
- self._emit('loaderror', null, 'No codec support for selected audio sources.');
977
- return;
978
- }
979
-
980
- self._src = url;
981
- self._state = 'loading';
982
-
983
- // If the hosting page is HTTPS and the source isn't,
984
- // drop down to HTML5 Audio to avoid Mixed Content errors.
985
- if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') {
986
- self._html5 = true;
987
- self._webAudio = false;
988
- }
989
-
990
- // Create a new sound object and add it to the pool.
991
- new Sound(self);
992
-
993
- // Load and decode the audio data for playback.
994
- if (self._webAudio) {
995
- loadBuffer(self);
996
- }
997
-
998
- return self;
999
- },
1000
-
1001
- /**
1002
- * Play a sound or resume previous playback.
1003
- * @param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
1004
- * @param {Boolean} internal Internal Use: true prevents event firing.
1005
- * @return {Number} Sound ID.
1006
- */
1007
- play: function(sprite, internal) {
1008
- var self = this;
1009
- var id = null;
1010
-
1011
- // Determine if a sprite, sound id or nothing was passed
1012
- if (typeof sprite === 'number') {
1013
- id = sprite;
1014
- sprite = null;
1015
- } else if (typeof sprite === 'string' && self._state === 'loaded' && !self._sprite[sprite]) {
1016
- // If the passed sprite doesn't exist, do nothing.
1017
- return null;
1018
- } else if (typeof sprite === 'undefined') {
1019
- // Use the default sound sprite (plays the full audio length).
1020
- sprite = '__default';
1021
-
1022
- // Check if there is a single paused sound that isn't ended.
1023
- // If there is, play that sound. If not, continue as usual.
1024
- if (!self._playLock) {
1025
- var num = 0;
1026
- for (var i=0; i<self._sounds.length; i++) {
1027
- if (self._sounds[i]._paused && !self._sounds[i]._ended) {
1028
- num++;
1029
- id = self._sounds[i]._id;
1030
- }
1031
- }
1032
-
1033
- if (num === 1) {
1034
- sprite = null;
1035
- } else {
1036
- id = null;
1037
- }
1038
- }
1039
- }
1040
-
1041
- // Get the selected node, or get one from the pool.
1042
- var sound = id ? self._soundById(id) : self._inactiveSound();
1043
-
1044
- // If the sound doesn't exist, do nothing.
1045
- if (!sound) {
1046
- return null;
1047
- }
1048
-
1049
- // Select the sprite definition.
1050
- if (id && !sprite) {
1051
- sprite = sound._sprite || '__default';
1052
- }
1053
-
1054
- // If the sound hasn't loaded, we must wait to get the audio's duration.
1055
- // We also need to wait to make sure we don't run into race conditions with
1056
- // the order of function calls.
1057
- if (self._state !== 'loaded') {
1058
- // Set the sprite value on this sound.
1059
- sound._sprite = sprite;
1060
-
1061
- // Mark this sound as not ended in case another sound is played before this one loads.
1062
- sound._ended = false;
1063
-
1064
- // Add the sound to the queue to be played on load.
1065
- var soundId = sound._id;
1066
- self._queue.push({
1067
- event: 'play',
1068
- action: function() {
1069
- self.play(soundId);
1070
- }
1071
- });
1072
-
1073
- return soundId;
1074
- }
1075
-
1076
- // Don't play the sound if an id was passed and it is already playing.
1077
- if (id && !sound._paused) {
1078
- // Trigger the play event, in order to keep iterating through queue.
1079
- if (!internal) {
1080
- self._loadQueue('play');
1081
- }
1082
-
1083
- return sound._id;
1084
- }
1085
-
1086
- // Make sure the AudioContext isn't suspended, and resume it if it is.
1087
- if (self._webAudio) {
1088
- Howler._autoResume();
1089
- }
1090
-
1091
- // Determine how long to play for and where to start playing.
1092
- var seek = Math.max(0, sound._seek > 0 ? sound._seek : self._sprite[sprite][0] / 1000);
1093
- var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek);
1094
- var timeout = (duration * 1000) / Math.abs(sound._rate);
1095
- var start = self._sprite[sprite][0] / 1000;
1096
- var stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000;
1097
- sound._sprite = sprite;
1098
-
1099
- // Mark the sound as ended instantly so that this async playback
1100
- // doesn't get grabbed by another call to play while this one waits to start.
1101
- sound._ended = false;
1102
-
1103
- // Update the parameters of the sound.
1104
- var setParams = function() {
1105
- sound._paused = false;
1106
- sound._seek = seek;
1107
- sound._start = start;
1108
- sound._stop = stop;
1109
- sound._loop = !!(sound._loop || self._sprite[sprite][2]);
1110
- };
1111
-
1112
- // End the sound instantly if seek is at the end.
1113
- if (seek >= stop) {
1114
- self._ended(sound);
1115
- return;
1116
- }
1117
-
1118
- // Begin the actual playback.
1119
- var node = sound._node;
1120
- if (self._webAudio) {
1121
- // Fire this when the sound is ready to play to begin Web Audio playback.
1122
- var playWebAudio = function() {
1123
- self._playLock = false;
1124
- setParams();
1125
- self._refreshBuffer(sound);
1126
-
1127
- // Setup the playback params.
1128
- var vol = (sound._muted || self._muted) ? 0 : sound._volume;
1129
- node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
1130
- sound._playStart = Howler.ctx.currentTime;
1131
-
1132
- // Play the sound using the supported method.
1133
- if (typeof node.bufferSource.start === 'undefined') {
1134
- sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
1135
- } else {
1136
- sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
1137
- }
1138
-
1139
- // Start a new timer if none is present.
1140
- if (timeout !== Infinity) {
1141
- self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
1142
- }
1143
-
1144
- if (!internal) {
1145
- setTimeout(function() {
1146
- self._emit('play', sound._id);
1147
- self._loadQueue();
1148
- }, 0);
1149
- }
1150
- };
1151
-
1152
- if (Howler.state === 'running' && Howler.ctx.state !== 'interrupted') {
1153
- playWebAudio();
1154
- } else {
1155
- self._playLock = true;
1156
-
1157
- // Wait for the audio context to resume before playing.
1158
- self.once('resume', playWebAudio);
1159
-
1160
- // Cancel the end timer.
1161
- self._clearTimer(sound._id);
1162
- }
1163
- } else {
1164
- // Fire this when the sound is ready to play to begin HTML5 Audio playback.
1165
- var playHtml5 = function() {
1166
- node.currentTime = seek;
1167
- node.muted = sound._muted || self._muted || Howler._muted || node.muted;
1168
- node.volume = sound._volume * Howler.volume();
1169
- node.playbackRate = sound._rate;
1170
-
1171
- // Some browsers will throw an error if this is called without user interaction.
1172
- try {
1173
- var play = node.play();
1174
-
1175
- // Support older browsers that don't support promises, and thus don't have this issue.
1176
- if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
1177
- // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
1178
- self._playLock = true;
1179
-
1180
- // Set param values immediately.
1181
- setParams();
1182
-
1183
- // Releases the lock and executes queued actions.
1184
- play
1185
- .then(function() {
1186
- self._playLock = false;
1187
- node._unlocked = true;
1188
- if (!internal) {
1189
- self._emit('play', sound._id);
1190
- } else {
1191
- self._loadQueue();
1192
- }
1193
- })
1194
- .catch(function() {
1195
- self._playLock = false;
1196
- self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
1197
- 'on mobile devices and Chrome where playback was not within a user interaction.');
1198
-
1199
- // Reset the ended and paused values.
1200
- sound._ended = true;
1201
- sound._paused = true;
1202
- });
1203
- } else if (!internal) {
1204
- self._playLock = false;
1205
- setParams();
1206
- self._emit('play', sound._id);
1207
- }
1208
-
1209
- // Setting rate before playing won't work in IE, so we set it again here.
1210
- node.playbackRate = sound._rate;
1211
-
1212
- // If the node is still paused, then we can assume there was a playback issue.
1213
- if (node.paused) {
1214
- self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
1215
- 'on mobile devices and Chrome where playback was not within a user interaction.');
1216
- return;
1217
- }
1218
-
1219
- // Setup the end timer on sprites or listen for the ended event.
1220
- if (sprite !== '__default' || sound._loop) {
1221
- self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
1222
- } else {
1223
- self._endTimers[sound._id] = function() {
1224
- // Fire ended on this audio node.
1225
- self._ended(sound);
1226
-
1227
- // Clear this listener.
1228
- node.removeEventListener('ended', self._endTimers[sound._id], false);
1229
- };
1230
- node.addEventListener('ended', self._endTimers[sound._id], false);
1231
- }
1232
- } catch (err) {
1233
- self._emit('playerror', sound._id, err);
1234
- }
1235
- };
1236
-
1237
- // If this is streaming audio, make sure the src is set and load again.
1238
- if (node.src === 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA') {
1239
- node.src = self._src;
1240
- node.load();
1241
- }
1242
-
1243
- // Play immediately if ready, or wait for the 'canplaythrough'e vent.
1244
- var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS);
1245
- if (node.readyState >= 3 || loadedNoReadyState) {
1246
- playHtml5();
1247
- } else {
1248
- self._playLock = true;
1249
- self._state = 'loading';
1250
-
1251
- var listener = function() {
1252
- self._state = 'loaded';
1253
-
1254
- // Begin playback.
1255
- playHtml5();
1256
-
1257
- // Clear this listener.
1258
- node.removeEventListener(Howler._canPlayEvent, listener, false);
1259
- };
1260
- node.addEventListener(Howler._canPlayEvent, listener, false);
1261
-
1262
- // Cancel the end timer.
1263
- self._clearTimer(sound._id);
1264
- }
1265
- }
1266
-
1267
- return sound._id;
1268
- },
1269
-
1270
- /**
1271
- * Pause playback and save current position.
1272
- * @param {Number} id The sound ID (empty to pause all in group).
1273
- * @return {Howl}
1274
- */
1275
- pause: function(id) {
1276
- var self = this;
1277
-
1278
- // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable.
1279
- if (self._state !== 'loaded' || self._playLock) {
1280
- self._queue.push({
1281
- event: 'pause',
1282
- action: function() {
1283
- self.pause(id);
1284
- }
1285
- });
1286
-
1287
- return self;
1288
- }
1289
-
1290
- // If no id is passed, get all ID's to be paused.
1291
- var ids = self._getSoundIds(id);
1292
-
1293
- for (var i=0; i<ids.length; i++) {
1294
- // Clear the end timer.
1295
- self._clearTimer(ids[i]);
1296
-
1297
- // Get the sound.
1298
- var sound = self._soundById(ids[i]);
1299
-
1300
- if (sound && !sound._paused) {
1301
- // Reset the seek position.
1302
- sound._seek = self.seek(ids[i]);
1303
- sound._rateSeek = 0;
1304
- sound._paused = true;
1305
-
1306
- // Stop currently running fades.
1307
- self._stopFade(ids[i]);
1308
-
1309
- if (sound._node) {
1310
- if (self._webAudio) {
1311
- // Make sure the sound has been created.
1312
- if (!sound._node.bufferSource) {
1313
- continue;
1314
- }
1315
-
1316
- if (typeof sound._node.bufferSource.stop === 'undefined') {
1317
- sound._node.bufferSource.noteOff(0);
1318
- } else {
1319
- sound._node.bufferSource.stop(0);
1320
- }
1321
-
1322
- // Clean up the buffer source.
1323
- self._cleanBuffer(sound._node);
1324
- } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
1325
- sound._node.pause();
1326
- }
1327
- }
1328
- }
1329
-
1330
- // Fire the pause event, unless `true` is passed as the 2nd argument.
1331
- if (!arguments[1]) {
1332
- self._emit('pause', sound ? sound._id : null);
1333
- }
1334
- }
1335
-
1336
- return self;
1337
- },
1338
-
1339
- /**
1340
- * Stop playback and reset to start.
1341
- * @param {Number} id The sound ID (empty to stop all in group).
1342
- * @param {Boolean} internal Internal Use: true prevents event firing.
1343
- * @return {Howl}
1344
- */
1345
- stop: function(id, internal) {
1346
- var self = this;
1347
-
1348
- // If the sound hasn't loaded, add it to the load queue to stop when capable.
1349
- if (self._state !== 'loaded' || self._playLock) {
1350
- self._queue.push({
1351
- event: 'stop',
1352
- action: function() {
1353
- self.stop(id);
1354
- }
1355
- });
1356
-
1357
- return self;
1358
- }
1359
-
1360
- // If no id is passed, get all ID's to be stopped.
1361
- var ids = self._getSoundIds(id);
1362
-
1363
- for (var i=0; i<ids.length; i++) {
1364
- // Clear the end timer.
1365
- self._clearTimer(ids[i]);
1366
-
1367
- // Get the sound.
1368
- var sound = self._soundById(ids[i]);
1369
-
1370
- if (sound) {
1371
- // Reset the seek position.
1372
- sound._seek = sound._start || 0;
1373
- sound._rateSeek = 0;
1374
- sound._paused = true;
1375
- sound._ended = true;
1376
-
1377
- // Stop currently running fades.
1378
- self._stopFade(ids[i]);
1379
-
1380
- if (sound._node) {
1381
- if (self._webAudio) {
1382
- // Make sure the sound's AudioBufferSourceNode has been created.
1383
- if (sound._node.bufferSource) {
1384
- if (typeof sound._node.bufferSource.stop === 'undefined') {
1385
- sound._node.bufferSource.noteOff(0);
1386
- } else {
1387
- sound._node.bufferSource.stop(0);
1388
- }
1389
-
1390
- // Clean up the buffer source.
1391
- self._cleanBuffer(sound._node);
1392
- }
1393
- } else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
1394
- sound._node.currentTime = sound._start || 0;
1395
- sound._node.pause();
1396
-
1397
- // If this is a live stream, stop download once the audio is stopped.
1398
- if (sound._node.duration === Infinity) {
1399
- self._clearSound(sound._node);
1400
- }
1401
- }
1402
- }
1403
-
1404
- if (!internal) {
1405
- self._emit('stop', sound._id);
1406
- }
1407
- }
1408
- }
1409
-
1410
- return self;
1411
- },
1412
-
1413
- /**
1414
- * Mute/unmute a single sound or all sounds in this Howl group.
1415
- * @param {Boolean} muted Set to true to mute and false to unmute.
1416
- * @param {Number} id The sound ID to update (omit to mute/unmute all).
1417
- * @return {Howl}
1418
- */
1419
- mute: function(muted, id) {
1420
- var self = this;
1421
-
1422
- // If the sound hasn't loaded, add it to the load queue to mute when capable.
1423
- if (self._state !== 'loaded'|| self._playLock) {
1424
- self._queue.push({
1425
- event: 'mute',
1426
- action: function() {
1427
- self.mute(muted, id);
1428
- }
1429
- });
1430
-
1431
- return self;
1432
- }
1433
-
1434
- // If applying mute/unmute to all sounds, update the group's value.
1435
- if (typeof id === 'undefined') {
1436
- if (typeof muted === 'boolean') {
1437
- self._muted = muted;
1438
- } else {
1439
- return self._muted;
1440
- }
1441
- }
1442
-
1443
- // If no id is passed, get all ID's to be muted.
1444
- var ids = self._getSoundIds(id);
1445
-
1446
- for (var i=0; i<ids.length; i++) {
1447
- // Get the sound.
1448
- var sound = self._soundById(ids[i]);
1449
-
1450
- if (sound) {
1451
- sound._muted = muted;
1452
-
1453
- // Cancel active fade and set the volume to the end value.
1454
- if (sound._interval) {
1455
- self._stopFade(sound._id);
1456
- }
1457
-
1458
- if (self._webAudio && sound._node) {
1459
- sound._node.gain.setValueAtTime(muted ? 0 : sound._volume, Howler.ctx.currentTime);
1460
- } else if (sound._node) {
1461
- sound._node.muted = Howler._muted ? true : muted;
1462
- }
1463
-
1464
- self._emit('mute', sound._id);
1465
- }
1466
- }
1467
-
1468
- return self;
1469
- },
1470
-
1471
- /**
1472
- * Get/set the volume of this sound or of the Howl group. This method can optionally take 0, 1 or 2 arguments.
1473
- * volume() -> Returns the group's volume value.
1474
- * volume(id) -> Returns the sound id's current volume.
1475
- * volume(vol) -> Sets the volume of all sounds in this Howl group.
1476
- * volume(vol, id) -> Sets the volume of passed sound id.
1477
- * @return {Howl/Number} Returns self or current volume.
1478
- */
1479
- volume: function() {
1480
- var self = this;
1481
- var args = arguments;
1482
- var vol, id;
1483
-
1484
- // Determine the values based on arguments.
1485
- if (args.length === 0) {
1486
- // Return the value of the groups' volume.
1487
- return self._volume;
1488
- } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') {
1489
- // First check if this is an ID, and if not, assume it is a new volume.
1490
- var ids = self._getSoundIds();
1491
- var index = ids.indexOf(args[0]);
1492
- if (index >= 0) {
1493
- id = parseInt(args[0], 10);
1494
- } else {
1495
- vol = parseFloat(args[0]);
1496
- }
1497
- } else if (args.length >= 2) {
1498
- vol = parseFloat(args[0]);
1499
- id = parseInt(args[1], 10);
1500
- }
1501
-
1502
- // Update the volume or return the current volume.
1503
- var sound;
1504
- if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
1505
- // If the sound hasn't loaded, add it to the load queue to change volume when capable.
1506
- if (self._state !== 'loaded'|| self._playLock) {
1507
- self._queue.push({
1508
- event: 'volume',
1509
- action: function() {
1510
- self.volume.apply(self, args);
1511
- }
1512
- });
1513
-
1514
- return self;
1515
- }
1516
-
1517
- // Set the group volume.
1518
- if (typeof id === 'undefined') {
1519
- self._volume = vol;
1520
- }
1521
-
1522
- // Update one or all volumes.
1523
- id = self._getSoundIds(id);
1524
- for (var i=0; i<id.length; i++) {
1525
- // Get the sound.
1526
- sound = self._soundById(id[i]);
1527
-
1528
- if (sound) {
1529
- sound._volume = vol;
1530
-
1531
- // Stop currently running fades.
1532
- if (!args[2]) {
1533
- self._stopFade(id[i]);
1534
- }
1535
-
1536
- if (self._webAudio && sound._node && !sound._muted) {
1537
- sound._node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
1538
- } else if (sound._node && !sound._muted) {
1539
- sound._node.volume = vol * Howler.volume();
1540
- }
1541
-
1542
- self._emit('volume', sound._id);
1543
- }
1544
- }
1545
- } else {
1546
- sound = id ? self._soundById(id) : self._sounds[0];
1547
- return sound ? sound._volume : 0;
1548
- }
1549
-
1550
- return self;
1551
- },
1552
-
1553
- /**
1554
- * Fade a currently playing sound between two volumes (if no id is passed, all sounds will fade).
1555
- * @param {Number} from The value to fade from (0.0 to 1.0).
1556
- * @param {Number} to The volume to fade to (0.0 to 1.0).
1557
- * @param {Number} len Time in milliseconds to fade.
1558
- * @param {Number} id The sound id (omit to fade all sounds).
1559
- * @return {Howl}
1560
- */
1561
- fade: function(from, to, len, id) {
1562
- var self = this;
1563
-
1564
- // If the sound hasn't loaded, add it to the load queue to fade when capable.
1565
- if (self._state !== 'loaded' || self._playLock) {
1566
- self._queue.push({
1567
- event: 'fade',
1568
- action: function() {
1569
- self.fade(from, to, len, id);
1570
- }
1571
- });
1572
-
1573
- return self;
1574
- }
1575
-
1576
- // Make sure the to/from/len values are numbers.
1577
- from = Math.min(Math.max(0, parseFloat(from)), 1);
1578
- to = Math.min(Math.max(0, parseFloat(to)), 1);
1579
- len = parseFloat(len);
1580
-
1581
- // Set the volume to the start position.
1582
- self.volume(from, id);
1583
-
1584
- // Fade the volume of one or all sounds.
1585
- var ids = self._getSoundIds(id);
1586
- for (var i=0; i<ids.length; i++) {
1587
- // Get the sound.
1588
- var sound = self._soundById(ids[i]);
1589
-
1590
- // Create a linear fade or fall back to timeouts with HTML5 Audio.
1591
- if (sound) {
1592
- // Stop the previous fade if no sprite is being used (otherwise, volume handles this).
1593
- if (!id) {
1594
- self._stopFade(ids[i]);
1595
- }
1596
-
1597
- // If we are using Web Audio, let the native methods do the actual fade.
1598
- if (self._webAudio && !sound._muted) {
1599
- var currentTime = Howler.ctx.currentTime;
1600
- var end = currentTime + (len / 1000);
1601
- sound._volume = from;
1602
- sound._node.gain.setValueAtTime(from, currentTime);
1603
- sound._node.gain.linearRampToValueAtTime(to, end);
1604
- }
1605
-
1606
- self._startFadeInterval(sound, from, to, len, ids[i], typeof id === 'undefined');
1607
- }
1608
- }
1609
-
1610
- return self;
1611
- },
1612
-
1613
- /**
1614
- * Starts the internal interval to fade a sound.
1615
- * @param {Object} sound Reference to sound to fade.
1616
- * @param {Number} from The value to fade from (0.0 to 1.0).
1617
- * @param {Number} to The volume to fade to (0.0 to 1.0).
1618
- * @param {Number} len Time in milliseconds to fade.
1619
- * @param {Number} id The sound id to fade.
1620
- * @param {Boolean} isGroup If true, set the volume on the group.
1621
- */
1622
- _startFadeInterval: function(sound, from, to, len, id, isGroup) {
1623
- var self = this;
1624
- var vol = from;
1625
- var diff = to - from;
1626
- var steps = Math.abs(diff / 0.01);
1627
- var stepLen = Math.max(4, (steps > 0) ? len / steps : len);
1628
- var lastTick = Date.now();
1629
-
1630
- // Store the value being faded to.
1631
- sound._fadeTo = to;
1632
-
1633
- // Update the volume value on each interval tick.
1634
- sound._interval = setInterval(function() {
1635
- // Update the volume based on the time since the last tick.
1636
- var tick = (Date.now() - lastTick) / len;
1637
- lastTick = Date.now();
1638
- vol += diff * tick;
1639
-
1640
- // Round to within 2 decimal points.
1641
- vol = Math.round(vol * 100) / 100;
1642
-
1643
- // Make sure the volume is in the right bounds.
1644
- if (diff < 0) {
1645
- vol = Math.max(to, vol);
1646
- } else {
1647
- vol = Math.min(to, vol);
1648
- }
1649
-
1650
- // Change the volume.
1651
- if (self._webAudio) {
1652
- sound._volume = vol;
1653
- } else {
1654
- self.volume(vol, sound._id, true);
1655
- }
1656
-
1657
- // Set the group's volume.
1658
- if (isGroup) {
1659
- self._volume = vol;
1660
- }
1661
-
1662
- // When the fade is complete, stop it and fire event.
1663
- if ((to < from && vol <= to) || (to > from && vol >= to)) {
1664
- clearInterval(sound._interval);
1665
- sound._interval = null;
1666
- sound._fadeTo = null;
1667
- self.volume(to, sound._id);
1668
- self._emit('fade', sound._id);
1669
- }
1670
- }, stepLen);
1671
- },
1672
-
1673
- /**
1674
- * Internal method that stops the currently playing fade when
1675
- * a new fade starts, volume is changed or the sound is stopped.
1676
- * @param {Number} id The sound id.
1677
- * @return {Howl}
1678
- */
1679
- _stopFade: function(id) {
1680
- var self = this;
1681
- var sound = self._soundById(id);
1682
-
1683
- if (sound && sound._interval) {
1684
- if (self._webAudio) {
1685
- sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime);
1686
- }
1687
-
1688
- clearInterval(sound._interval);
1689
- sound._interval = null;
1690
- self.volume(sound._fadeTo, id);
1691
- sound._fadeTo = null;
1692
- self._emit('fade', id);
1693
- }
1694
-
1695
- return self;
1696
- },
1697
-
1698
- /**
1699
- * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments.
1700
- * loop() -> Returns the group's loop value.
1701
- * loop(id) -> Returns the sound id's loop value.
1702
- * loop(loop) -> Sets the loop value for all sounds in this Howl group.
1703
- * loop(loop, id) -> Sets the loop value of passed sound id.
1704
- * @return {Howl/Boolean} Returns self or current loop value.
1705
- */
1706
- loop: function() {
1707
- var self = this;
1708
- var args = arguments;
1709
- var loop, id, sound;
1710
-
1711
- // Determine the values for loop and id.
1712
- if (args.length === 0) {
1713
- // Return the grou's loop value.
1714
- return self._loop;
1715
- } else if (args.length === 1) {
1716
- if (typeof args[0] === 'boolean') {
1717
- loop = args[0];
1718
- self._loop = loop;
1719
- } else {
1720
- // Return this sound's loop value.
1721
- sound = self._soundById(parseInt(args[0], 10));
1722
- return sound ? sound._loop : false;
1723
- }
1724
- } else if (args.length === 2) {
1725
- loop = args[0];
1726
- id = parseInt(args[1], 10);
1727
- }
1728
-
1729
- // If no id is passed, get all ID's to be looped.
1730
- var ids = self._getSoundIds(id);
1731
- for (var i=0; i<ids.length; i++) {
1732
- sound = self._soundById(ids[i]);
1733
-
1734
- if (sound) {
1735
- sound._loop = loop;
1736
- if (self._webAudio && sound._node && sound._node.bufferSource) {
1737
- sound._node.bufferSource.loop = loop;
1738
- if (loop) {
1739
- sound._node.bufferSource.loopStart = sound._start || 0;
1740
- sound._node.bufferSource.loopEnd = sound._stop;
1741
-
1742
- // If playing, restart playback to ensure looping updates.
1743
- if (self.playing(ids[i])) {
1744
- self.pause(ids[i], true);
1745
- self.play(ids[i], true);
1746
- }
1747
- }
1748
- }
1749
- }
1750
- }
1751
-
1752
- return self;
1753
- },
1754
-
1755
- /**
1756
- * Get/set the playback rate of a sound. This method can optionally take 0, 1 or 2 arguments.
1757
- * rate() -> Returns the first sound node's current playback rate.
1758
- * rate(id) -> Returns the sound id's current playback rate.
1759
- * rate(rate) -> Sets the playback rate of all sounds in this Howl group.
1760
- * rate(rate, id) -> Sets the playback rate of passed sound id.
1761
- * @return {Howl/Number} Returns self or the current playback rate.
1762
- */
1763
- rate: function() {
1764
- var self = this;
1765
- var args = arguments;
1766
- var rate, id;
1767
-
1768
- // Determine the values based on arguments.
1769
- if (args.length === 0) {
1770
- // We will simply return the current rate of the first node.
1771
- id = self._sounds[0]._id;
1772
- } else if (args.length === 1) {
1773
- // First check if this is an ID, and if not, assume it is a new rate value.
1774
- var ids = self._getSoundIds();
1775
- var index = ids.indexOf(args[0]);
1776
- if (index >= 0) {
1777
- id = parseInt(args[0], 10);
1778
- } else {
1779
- rate = parseFloat(args[0]);
1780
- }
1781
- } else if (args.length === 2) {
1782
- rate = parseFloat(args[0]);
1783
- id = parseInt(args[1], 10);
1784
- }
1785
-
1786
- // Update the playback rate or return the current value.
1787
- var sound;
1788
- if (typeof rate === 'number') {
1789
- // If the sound hasn't loaded, add it to the load queue to change playback rate when capable.
1790
- if (self._state !== 'loaded' || self._playLock) {
1791
- self._queue.push({
1792
- event: 'rate',
1793
- action: function() {
1794
- self.rate.apply(self, args);
1795
- }
1796
- });
1797
-
1798
- return self;
1799
- }
1800
-
1801
- // Set the group rate.
1802
- if (typeof id === 'undefined') {
1803
- self._rate = rate;
1804
- }
1805
-
1806
- // Update one or all volumes.
1807
- id = self._getSoundIds(id);
1808
- for (var i=0; i<id.length; i++) {
1809
- // Get the sound.
1810
- sound = self._soundById(id[i]);
1811
-
1812
- if (sound) {
1813
- // Keep track of our position when the rate changed and update the playback
1814
- // start position so we can properly adjust the seek position for time elapsed.
1815
- if (self.playing(id[i])) {
1816
- sound._rateSeek = self.seek(id[i]);
1817
- sound._playStart = self._webAudio ? Howler.ctx.currentTime : sound._playStart;
1818
- }
1819
- sound._rate = rate;
1820
-
1821
- // Change the playback rate.
1822
- if (self._webAudio && sound._node && sound._node.bufferSource) {
1823
- sound._node.bufferSource.playbackRate.setValueAtTime(rate, Howler.ctx.currentTime);
1824
- } else if (sound._node) {
1825
- sound._node.playbackRate = rate;
1826
- }
1827
-
1828
- // Reset the timers.
1829
- var seek = self.seek(id[i]);
1830
- var duration = ((self._sprite[sound._sprite][0] + self._sprite[sound._sprite][1]) / 1000) - seek;
1831
- var timeout = (duration * 1000) / Math.abs(sound._rate);
1832
-
1833
- // Start a new end timer if sound is already playing.
1834
- if (self._endTimers[id[i]] || !sound._paused) {
1835
- self._clearTimer(id[i]);
1836
- self._endTimers[id[i]] = setTimeout(self._ended.bind(self, sound), timeout);
1837
- }
1838
-
1839
- self._emit('rate', sound._id);
1840
- }
1841
- }
1842
- } else {
1843
- sound = self._soundById(id);
1844
- return sound ? sound._rate : self._rate;
1845
- }
1846
-
1847
- return self;
1848
- },
1849
-
1850
- /**
1851
- * Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
1852
- * seek() -> Returns the first sound node's current seek position.
1853
- * seek(id) -> Returns the sound id's current seek position.
1854
- * seek(seek) -> Sets the seek position of the first sound node.
1855
- * seek(seek, id) -> Sets the seek position of passed sound id.
1856
- * @return {Howl/Number} Returns self or the current seek position.
1857
- */
1858
- seek: function() {
1859
- var self = this;
1860
- var args = arguments;
1861
- var seek, id;
1862
-
1863
- // Determine the values based on arguments.
1864
- if (args.length === 0) {
1865
- // We will simply return the current position of the first node.
1866
- if (self._sounds.length) {
1867
- id = self._sounds[0]._id;
1868
- }
1869
- } else if (args.length === 1) {
1870
- // First check if this is an ID, and if not, assume it is a new seek position.
1871
- var ids = self._getSoundIds();
1872
- var index = ids.indexOf(args[0]);
1873
- if (index >= 0) {
1874
- id = parseInt(args[0], 10);
1875
- } else if (self._sounds.length) {
1876
- id = self._sounds[0]._id;
1877
- seek = parseFloat(args[0]);
1878
- }
1879
- } else if (args.length === 2) {
1880
- seek = parseFloat(args[0]);
1881
- id = parseInt(args[1], 10);
1882
- }
1883
-
1884
- // If there is no ID, bail out.
1885
- if (typeof id === 'undefined') {
1886
- return 0;
1887
- }
1888
-
1889
- // If the sound hasn't loaded, add it to the load queue to seek when capable.
1890
- if (typeof seek === 'number' && (self._state !== 'loaded' || self._playLock)) {
1891
- self._queue.push({
1892
- event: 'seek',
1893
- action: function() {
1894
- self.seek.apply(self, args);
1895
- }
1896
- });
1897
-
1898
- return self;
1899
- }
1900
-
1901
- // Get the sound.
1902
- var sound = self._soundById(id);
1903
-
1904
- if (sound) {
1905
- if (typeof seek === 'number' && seek >= 0) {
1906
- // Pause the sound and update position for restarting playback.
1907
- var playing = self.playing(id);
1908
- if (playing) {
1909
- self.pause(id, true);
1910
- }
1911
-
1912
- // Move the position of the track and cancel timer.
1913
- sound._seek = seek;
1914
- sound._ended = false;
1915
- self._clearTimer(id);
1916
-
1917
- // Update the seek position for HTML5 Audio.
1918
- if (!self._webAudio && sound._node && !isNaN(sound._node.duration)) {
1919
- sound._node.currentTime = seek;
1920
- }
1921
-
1922
- // Seek and emit when ready.
1923
- var seekAndEmit = function() {
1924
- // Restart the playback if the sound was playing.
1925
- if (playing) {
1926
- self.play(id, true);
1927
- }
1928
-
1929
- self._emit('seek', id);
1930
- };
1931
-
1932
- // Wait for the play lock to be unset before emitting (HTML5 Audio).
1933
- if (playing && !self._webAudio) {
1934
- var emitSeek = function() {
1935
- if (!self._playLock) {
1936
- seekAndEmit();
1937
- } else {
1938
- setTimeout(emitSeek, 0);
1939
- }
1940
- };
1941
- setTimeout(emitSeek, 0);
1942
- } else {
1943
- seekAndEmit();
1944
- }
1945
- } else {
1946
- if (self._webAudio) {
1947
- var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0;
1948
- var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0;
1949
- return sound._seek + (rateSeek + realTime * Math.abs(sound._rate));
1950
- } else {
1951
- return sound._node.currentTime;
1952
- }
1953
- }
1954
- }
1955
-
1956
- return self;
1957
- },
1958
-
1959
- /**
1960
- * Check if a specific sound is currently playing or not (if id is provided), or check if at least one of the sounds in the group is playing or not.
1961
- * @param {Number} id The sound id to check. If none is passed, the whole sound group is checked.
1962
- * @return {Boolean} True if playing and false if not.
1963
- */
1964
- playing: function(id) {
1965
- var self = this;
1966
-
1967
- // Check the passed sound ID (if any).
1968
- if (typeof id === 'number') {
1969
- var sound = self._soundById(id);
1970
- return sound ? !sound._paused : false;
1971
- }
1972
-
1973
- // Otherwise, loop through all sounds and check if any are playing.
1974
- for (var i=0; i<self._sounds.length; i++) {
1975
- if (!self._sounds[i]._paused) {
1976
- return true;
1977
- }
1978
- }
1979
-
1980
- return false;
1981
- },
1982
-
1983
- /**
1984
- * Get the duration of this sound. Passing a sound id will return the sprite duration.
1985
- * @param {Number} id The sound id to check. If none is passed, return full source duration.
1986
- * @return {Number} Audio duration in seconds.
1987
- */
1988
- duration: function(id) {
1989
- var self = this;
1990
- var duration = self._duration;
1991
-
1992
- // If we pass an ID, get the sound and return the sprite length.
1993
- var sound = self._soundById(id);
1994
- if (sound) {
1995
- duration = self._sprite[sound._sprite][1] / 1000;
1996
- }
1997
-
1998
- return duration;
1999
- },
2000
-
2001
- /**
2002
- * Returns the current loaded state of this Howl.
2003
- * @return {String} 'unloaded', 'loading', 'loaded'
2004
- */
2005
- state: function() {
2006
- return this._state;
2007
- },
2008
-
2009
- /**
2010
- * Unload and destroy the current Howl object.
2011
- * This will immediately stop all sound instances attached to this group.
2012
- */
2013
- unload: function() {
2014
- var self = this;
2015
-
2016
- // Stop playing any active sounds.
2017
- var sounds = self._sounds;
2018
- for (var i=0; i<sounds.length; i++) {
2019
- // Stop the sound if it is currently playing.
2020
- if (!sounds[i]._paused) {
2021
- self.stop(sounds[i]._id);
2022
- }
2023
-
2024
- // Remove the source or disconnect.
2025
- if (!self._webAudio) {
2026
- // Set the source to 0-second silence to stop any downloading (except in IE).
2027
- self._clearSound(sounds[i]._node);
2028
-
2029
- // Remove any event listeners.
2030
- sounds[i]._node.removeEventListener('error', sounds[i]._errorFn, false);
2031
- sounds[i]._node.removeEventListener(Howler._canPlayEvent, sounds[i]._loadFn, false);
2032
- sounds[i]._node.removeEventListener('ended', sounds[i]._endFn, false);
2033
-
2034
- // Release the Audio object back to the pool.
2035
- Howler._releaseHtml5Audio(sounds[i]._node);
2036
- }
2037
-
2038
- // Empty out all of the nodes.
2039
- delete sounds[i]._node;
2040
-
2041
- // Make sure all timers are cleared out.
2042
- self._clearTimer(sounds[i]._id);
2043
- }
2044
-
2045
- // Remove the references in the global Howler object.
2046
- var index = Howler._howls.indexOf(self);
2047
- if (index >= 0) {
2048
- Howler._howls.splice(index, 1);
2049
- }
2050
-
2051
- // Delete this sound from the cache (if no other Howl is using it).
2052
- var remCache = true;
2053
- for (i=0; i<Howler._howls.length; i++) {
2054
- if (Howler._howls[i]._src === self._src || self._src.indexOf(Howler._howls[i]._src) >= 0) {
2055
- remCache = false;
2056
- break;
2057
- }
2058
- }
2059
-
2060
- if (cache && remCache) {
2061
- delete cache[self._src];
2062
- }
2063
-
2064
- // Clear global errors.
2065
- Howler.noAudio = false;
2066
-
2067
- // Clear out `self`.
2068
- self._state = 'unloaded';
2069
- self._sounds = [];
2070
- self = null;
2071
-
2072
- return null;
2073
- },
2074
-
2075
- /**
2076
- * Listen to a custom event.
2077
- * @param {String} event Event name.
2078
- * @param {Function} fn Listener to call.
2079
- * @param {Number} id (optional) Only listen to events for this sound.
2080
- * @param {Number} once (INTERNAL) Marks event to fire only once.
2081
- * @return {Howl}
2082
- */
2083
- on: function(event, fn, id, once) {
2084
- var self = this;
2085
- var events = self['_on' + event];
2086
-
2087
- if (typeof fn === 'function') {
2088
- events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn});
2089
- }
2090
-
2091
- return self;
2092
- },
2093
-
2094
- /**
2095
- * Remove a custom event. Call without parameters to remove all events.
2096
- * @param {String} event Event name.
2097
- * @param {Function} fn Listener to remove. Leave empty to remove all.
2098
- * @param {Number} id (optional) Only remove events for this sound.
2099
- * @return {Howl}
2100
- */
2101
- off: function(event, fn, id) {
2102
- var self = this;
2103
- var events = self['_on' + event];
2104
- var i = 0;
2105
-
2106
- // Allow passing just an event and ID.
2107
- if (typeof fn === 'number') {
2108
- id = fn;
2109
- fn = null;
2110
- }
2111
-
2112
- if (fn || id) {
2113
- // Loop through event store and remove the passed function.
2114
- for (i=0; i<events.length; i++) {
2115
- var isId = (id === events[i].id);
2116
- if (fn === events[i].fn && isId || !fn && isId) {
2117
- events.splice(i, 1);
2118
- break;
2119
- }
2120
- }
2121
- } else if (event) {
2122
- // Clear out all events of this type.
2123
- self['_on' + event] = [];
2124
- } else {
2125
- // Clear out all events of every type.
2126
- var keys = Object.keys(self);
2127
- for (i=0; i<keys.length; i++) {
2128
- if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) {
2129
- self[keys[i]] = [];
2130
- }
2131
- }
2132
- }
2133
-
2134
- return self;
2135
- },
2136
-
2137
- /**
2138
- * Listen to a custom event and remove it once fired.
2139
- * @param {String} event Event name.
2140
- * @param {Function} fn Listener to call.
2141
- * @param {Number} id (optional) Only listen to events for this sound.
2142
- * @return {Howl}
2143
- */
2144
- once: function(event, fn, id) {
2145
- var self = this;
2146
-
2147
- // Setup the event listener.
2148
- self.on(event, fn, id, 1);
2149
-
2150
- return self;
2151
- },
2152
-
2153
- /**
2154
- * Emit all events of a specific type and pass the sound id.
2155
- * @param {String} event Event name.
2156
- * @param {Number} id Sound ID.
2157
- * @param {Number} msg Message to go with event.
2158
- * @return {Howl}
2159
- */
2160
- _emit: function(event, id, msg) {
2161
- var self = this;
2162
- var events = self['_on' + event];
2163
-
2164
- // Loop through event store and fire all functions.
2165
- for (var i=events.length-1; i>=0; i--) {
2166
- // Only fire the listener if the correct ID is used.
2167
- if (!events[i].id || events[i].id === id || event === 'load') {
2168
- setTimeout(function(fn) {
2169
- fn.call(this, id, msg);
2170
- }.bind(self, events[i].fn), 0);
2171
-
2172
- // If this event was setup with `once`, remove it.
2173
- if (events[i].once) {
2174
- self.off(event, events[i].fn, events[i].id);
2175
- }
2176
- }
2177
- }
2178
-
2179
- // Pass the event type into load queue so that it can continue stepping.
2180
- self._loadQueue(event);
2181
-
2182
- return self;
2183
- },
2184
-
2185
- /**
2186
- * Queue of actions initiated before the sound has loaded.
2187
- * These will be called in sequence, with the next only firing
2188
- * after the previous has finished executing (even if async like play).
2189
- * @return {Howl}
2190
- */
2191
- _loadQueue: function(event) {
2192
- var self = this;
2193
-
2194
- if (self._queue.length > 0) {
2195
- var task = self._queue[0];
2196
-
2197
- // Remove this task if a matching event was passed.
2198
- if (task.event === event) {
2199
- self._queue.shift();
2200
- self._loadQueue();
2201
- }
2202
-
2203
- // Run the task if no event type is passed.
2204
- if (!event) {
2205
- task.action();
2206
- }
2207
- }
2208
-
2209
- return self;
2210
- },
2211
-
2212
- /**
2213
- * Fired when playback ends at the end of the duration.
2214
- * @param {Sound} sound The sound object to work with.
2215
- * @return {Howl}
2216
- */
2217
- _ended: function(sound) {
2218
- var self = this;
2219
- var sprite = sound._sprite;
2220
-
2221
- // If we are using IE and there was network latency we may be clipping
2222
- // audio before it completes playing. Lets check the node to make sure it
2223
- // believes it has completed, before ending the playback.
2224
- if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) {
2225
- setTimeout(self._ended.bind(self, sound), 100);
2226
- return self;
2227
- }
2228
-
2229
- // Should this sound loop?
2230
- var loop = !!(sound._loop || self._sprite[sprite][2]);
2231
-
2232
- // Fire the ended event.
2233
- self._emit('end', sound._id);
2234
-
2235
- // Restart the playback for HTML5 Audio loop.
2236
- if (!self._webAudio && loop) {
2237
- self.stop(sound._id, true).play(sound._id);
2238
- }
2239
-
2240
- // Restart this timer if on a Web Audio loop.
2241
- if (self._webAudio && loop) {
2242
- self._emit('play', sound._id);
2243
- sound._seek = sound._start || 0;
2244
- sound._rateSeek = 0;
2245
- sound._playStart = Howler.ctx.currentTime;
2246
-
2247
- var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate);
2248
- self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
2249
- }
2250
-
2251
- // Mark the node as paused.
2252
- if (self._webAudio && !loop) {
2253
- sound._paused = true;
2254
- sound._ended = true;
2255
- sound._seek = sound._start || 0;
2256
- sound._rateSeek = 0;
2257
- self._clearTimer(sound._id);
2258
-
2259
- // Clean up the buffer source.
2260
- self._cleanBuffer(sound._node);
2261
-
2262
- // Attempt to auto-suspend AudioContext if no sounds are still playing.
2263
- Howler._autoSuspend();
2264
- }
2265
-
2266
- // When using a sprite, end the track.
2267
- if (!self._webAudio && !loop) {
2268
- self.stop(sound._id, true);
2269
- }
2270
-
2271
- return self;
2272
- },
2273
-
2274
- /**
2275
- * Clear the end timer for a sound playback.
2276
- * @param {Number} id The sound ID.
2277
- * @return {Howl}
2278
- */
2279
- _clearTimer: function(id) {
2280
- var self = this;
2281
-
2282
- if (self._endTimers[id]) {
2283
- // Clear the timeout or remove the ended listener.
2284
- if (typeof self._endTimers[id] !== 'function') {
2285
- clearTimeout(self._endTimers[id]);
2286
- } else {
2287
- var sound = self._soundById(id);
2288
- if (sound && sound._node) {
2289
- sound._node.removeEventListener('ended', self._endTimers[id], false);
2290
- }
2291
- }
2292
-
2293
- delete self._endTimers[id];
2294
- }
2295
-
2296
- return self;
2297
- },
2298
-
2299
- /**
2300
- * Return the sound identified by this ID, or return null.
2301
- * @param {Number} id Sound ID
2302
- * @return {Object} Sound object or null.
2303
- */
2304
- _soundById: function(id) {
2305
- var self = this;
2306
-
2307
- // Loop through all sounds and find the one with this ID.
2308
- for (var i=0; i<self._sounds.length; i++) {
2309
- if (id === self._sounds[i]._id) {
2310
- return self._sounds[i];
2311
- }
2312
- }
2313
-
2314
- return null;
2315
- },
2316
-
2317
- /**
2318
- * Return an inactive sound from the pool or create a new one.
2319
- * @return {Sound} Sound playback object.
2320
- */
2321
- _inactiveSound: function() {
2322
- var self = this;
2323
-
2324
- self._drain();
2325
-
2326
- // Find the first inactive node to recycle.
2327
- for (var i=0; i<self._sounds.length; i++) {
2328
- if (self._sounds[i]._ended) {
2329
- return self._sounds[i].reset();
2330
- }
2331
- }
2332
-
2333
- // If no inactive node was found, create a new one.
2334
- return new Sound(self);
2335
- },
2336
-
2337
- /**
2338
- * Drain excess inactive sounds from the pool.
2339
- */
2340
- _drain: function() {
2341
- var self = this;
2342
- var limit = self._pool;
2343
- var cnt = 0;
2344
- var i = 0;
2345
-
2346
- // If there are less sounds than the max pool size, we are done.
2347
- if (self._sounds.length < limit) {
2348
- return;
2349
- }
2350
-
2351
- // Count the number of inactive sounds.
2352
- for (i=0; i<self._sounds.length; i++) {
2353
- if (self._sounds[i]._ended) {
2354
- cnt++;
2355
- }
2356
- }
2357
-
2358
- // Remove excess inactive sounds, going in reverse order.
2359
- for (i=self._sounds.length - 1; i>=0; i--) {
2360
- if (cnt <= limit) {
2361
- return;
2362
- }
2363
-
2364
- if (self._sounds[i]._ended) {
2365
- // Disconnect the audio source when using Web Audio.
2366
- if (self._webAudio && self._sounds[i]._node) {
2367
- self._sounds[i]._node.disconnect(0);
2368
- }
2369
-
2370
- // Remove sounds until we have the pool size.
2371
- self._sounds.splice(i, 1);
2372
- cnt--;
2373
- }
2374
- }
2375
- },
2376
-
2377
- /**
2378
- * Get all ID's from the sounds pool.
2379
- * @param {Number} id Only return one ID if one is passed.
2380
- * @return {Array} Array of IDs.
2381
- */
2382
- _getSoundIds: function(id) {
2383
- var self = this;
2384
-
2385
- if (typeof id === 'undefined') {
2386
- var ids = [];
2387
- for (var i=0; i<self._sounds.length; i++) {
2388
- ids.push(self._sounds[i]._id);
2389
- }
2390
-
2391
- return ids;
2392
- } else {
2393
- return [id];
2394
- }
2395
- },
2396
-
2397
- /**
2398
- * Load the sound back into the buffer source.
2399
- * @param {Sound} sound The sound object to work with.
2400
- * @return {Howl}
2401
- */
2402
- _refreshBuffer: function(sound) {
2403
- var self = this;
2404
-
2405
- // Setup the buffer source for playback.
2406
- sound._node.bufferSource = Howler.ctx.createBufferSource();
2407
- sound._node.bufferSource.buffer = cache[self._src];
2408
-
2409
- // Connect to the correct node.
2410
- if (sound._panner) {
2411
- sound._node.bufferSource.connect(sound._panner);
2412
- } else {
2413
- sound._node.bufferSource.connect(sound._node);
2414
- }
2415
-
2416
- // Setup looping and playback rate.
2417
- sound._node.bufferSource.loop = sound._loop;
2418
- if (sound._loop) {
2419
- sound._node.bufferSource.loopStart = sound._start || 0;
2420
- sound._node.bufferSource.loopEnd = sound._stop || 0;
2421
- }
2422
- sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime);
2423
-
2424
- return self;
2425
- },
2426
-
2427
- /**
2428
- * Prevent memory leaks by cleaning up the buffer source after playback.
2429
- * @param {Object} node Sound's audio node containing the buffer source.
2430
- * @return {Howl}
2431
- */
2432
- _cleanBuffer: function(node) {
2433
- var self = this;
2434
- var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0;
2435
-
2436
- if (!node.bufferSource) {
2437
- return self;
2438
- }
2439
-
2440
- if (Howler._scratchBuffer && node.bufferSource) {
2441
- node.bufferSource.onended = null;
2442
- node.bufferSource.disconnect(0);
2443
- if (isIOS) {
2444
- try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {}
2445
- }
2446
- }
2447
- node.bufferSource = null;
2448
-
2449
- return self;
2450
- },
2451
-
2452
- /**
2453
- * Set the source to a 0-second silence to stop any downloading (except in IE).
2454
- * @param {Object} node Audio node to clear.
2455
- */
2456
- _clearSound: function(node) {
2457
- var checkIE = /MSIE |Trident\//.test(Howler._navigator && Howler._navigator.userAgent);
2458
- if (!checkIE) {
2459
- node.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
2460
- }
2461
- }
2462
- };
2463
-
2464
- /** Single Sound Methods **/
2465
- /***************************************************************************/
2466
-
2467
- /**
2468
- * Setup the sound object, which each node attached to a Howl group is contained in.
2469
- * @param {Object} howl The Howl parent group.
2470
- */
2471
- var Sound = function(howl) {
2472
- this._parent = howl;
2473
- this.init();
2474
- };
2475
- Sound.prototype = {
2476
- /**
2477
- * Initialize a new Sound object.
2478
- * @return {Sound}
2479
- */
2480
- init: function() {
2481
- var self = this;
2482
- var parent = self._parent;
2483
-
2484
- // Setup the default parameters.
2485
- self._muted = parent._muted;
2486
- self._loop = parent._loop;
2487
- self._volume = parent._volume;
2488
- self._rate = parent._rate;
2489
- self._seek = 0;
2490
- self._paused = true;
2491
- self._ended = true;
2492
- self._sprite = '__default';
2493
-
2494
- // Generate a unique ID for this sound.
2495
- self._id = ++Howler._counter;
2496
-
2497
- // Add itself to the parent's pool.
2498
- parent._sounds.push(self);
2499
-
2500
- // Create the new node.
2501
- self.create();
2502
-
2503
- return self;
2504
- },
2505
-
2506
- /**
2507
- * Create and setup a new sound object, whether HTML5 Audio or Web Audio.
2508
- * @return {Sound}
2509
- */
2510
- create: function() {
2511
- var self = this;
2512
- var parent = self._parent;
2513
- var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume;
2514
-
2515
- if (parent._webAudio) {
2516
- // Create the gain node for controlling volume (the source will connect to this).
2517
- self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
2518
- self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime);
2519
- self._node.paused = true;
2520
- self._node.connect(Howler.masterGain);
2521
- } else if (!Howler.noAudio) {
2522
- // Get an unlocked Audio object from the pool.
2523
- self._node = Howler._obtainHtml5Audio();
2524
-
2525
- // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror).
2526
- self._errorFn = self._errorListener.bind(self);
2527
- self._node.addEventListener('error', self._errorFn, false);
2528
-
2529
- // Listen for 'canplaythrough' event to let us know the sound is ready.
2530
- self._loadFn = self._loadListener.bind(self);
2531
- self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false);
2532
-
2533
- // Listen for the 'ended' event on the sound to account for edge-case where
2534
- // a finite sound has a duration of Infinity.
2535
- self._endFn = self._endListener.bind(self);
2536
- self._node.addEventListener('ended', self._endFn, false);
2537
-
2538
- // Setup the new audio node.
2539
- self._node.src = parent._src;
2540
- self._node.preload = parent._preload === true ? 'auto' : parent._preload;
2541
- self._node.volume = volume * Howler.volume();
2542
-
2543
- // Begin loading the source.
2544
- self._node.load();
2545
- }
2546
-
2547
- return self;
2548
- },
2549
-
2550
- /**
2551
- * Reset the parameters of this sound to the original state (for recycle).
2552
- * @return {Sound}
2553
- */
2554
- reset: function() {
2555
- var self = this;
2556
- var parent = self._parent;
2557
-
2558
- // Reset all of the parameters of this sound.
2559
- self._muted = parent._muted;
2560
- self._loop = parent._loop;
2561
- self._volume = parent._volume;
2562
- self._rate = parent._rate;
2563
- self._seek = 0;
2564
- self._rateSeek = 0;
2565
- self._paused = true;
2566
- self._ended = true;
2567
- self._sprite = '__default';
2568
-
2569
- // Generate a new ID so that it isn't confused with the previous sound.
2570
- self._id = ++Howler._counter;
2571
-
2572
- return self;
2573
- },
2574
-
2575
- /**
2576
- * HTML5 Audio error listener callback.
2577
- */
2578
- _errorListener: function() {
2579
- var self = this;
2580
-
2581
- // Fire an error event and pass back the code.
2582
- self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0);
2583
-
2584
- // Clear the event listener.
2585
- self._node.removeEventListener('error', self._errorFn, false);
2586
- },
2587
-
2588
- /**
2589
- * HTML5 Audio canplaythrough listener callback.
2590
- */
2591
- _loadListener: function() {
2592
- var self = this;
2593
- var parent = self._parent;
2594
-
2595
- // Round up the duration to account for the lower precision in HTML5 Audio.
2596
- parent._duration = Math.ceil(self._node.duration * 10) / 10;
2597
-
2598
- // Setup a sprite if none is defined.
2599
- if (Object.keys(parent._sprite).length === 0) {
2600
- parent._sprite = {__default: [0, parent._duration * 1000]};
2601
- }
2602
-
2603
- if (parent._state !== 'loaded') {
2604
- parent._state = 'loaded';
2605
- parent._emit('load');
2606
- parent._loadQueue();
2607
- }
2608
-
2609
- // Clear the event listener.
2610
- self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
2611
- },
2612
-
2613
- /**
2614
- * HTML5 Audio ended listener callback.
2615
- */
2616
- _endListener: function() {
2617
- var self = this;
2618
- var parent = self._parent;
2619
-
2620
- // Only handle the `ended`` event if the duration is Infinity.
2621
- if (parent._duration === Infinity) {
2622
- // Update the parent duration to match the real audio duration.
2623
- // Round up the duration to account for the lower precision in HTML5 Audio.
2624
- parent._duration = Math.ceil(self._node.duration * 10) / 10;
2625
-
2626
- // Update the sprite that corresponds to the real duration.
2627
- if (parent._sprite.__default[1] === Infinity) {
2628
- parent._sprite.__default[1] = parent._duration * 1000;
2629
- }
2630
-
2631
- // Run the regular ended method.
2632
- parent._ended(self);
2633
- }
2634
-
2635
- // Clear the event listener since the duration is now correct.
2636
- self._node.removeEventListener('ended', self._endFn, false);
2637
- }
2638
- };
2639
-
2640
- /** Helper Methods **/
2641
- /***************************************************************************/
2642
-
2643
- var cache = {};
2644
-
2645
- /**
2646
- * Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
2647
- * @param {Howl} self
2648
- */
2649
- var loadBuffer = function(self) {
2650
- var url = self._src;
2651
-
2652
- // Check if the buffer has already been cached and use it instead.
2653
- if (cache[url]) {
2654
- // Set the duration from the cache.
2655
- self._duration = cache[url].duration;
2656
-
2657
- // Load the sound into this Howl.
2658
- loadSound(self);
2659
-
2660
- return;
2661
- }
2662
-
2663
- if (/^data:[^;]+;base64,/.test(url)) {
2664
- // Decode the base64 data URI without XHR, since some browsers don't support it.
2665
- var data = atob(url.split(',')[1]);
2666
- var dataView = new Uint8Array(data.length);
2667
- for (var i=0; i<data.length; ++i) {
2668
- dataView[i] = data.charCodeAt(i);
2669
- }
2670
-
2671
- decodeAudioData(dataView.buffer, self);
2672
- } else {
2673
- // Load the buffer from the URL.
2674
- var xhr = new XMLHttpRequest();
2675
- xhr.open(self._xhr.method, url, true);
2676
- xhr.withCredentials = self._xhr.withCredentials;
2677
- xhr.responseType = 'arraybuffer';
2678
-
2679
- // Apply any custom headers to the request.
2680
- if (self._xhr.headers) {
2681
- Object.keys(self._xhr.headers).forEach(function(key) {
2682
- xhr.setRequestHeader(key, self._xhr.headers[key]);
2683
- });
2684
- }
2685
-
2686
- xhr.onload = function() {
2687
- // Make sure we get a successful response back.
2688
- var code = (xhr.status + '')[0];
2689
- if (code !== '0' && code !== '2' && code !== '3') {
2690
- self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
2691
- return;
2692
- }
2693
-
2694
- decodeAudioData(xhr.response, self);
2695
- };
2696
- xhr.onerror = function() {
2697
- // If there is an error, switch to HTML5 Audio.
2698
- if (self._webAudio) {
2699
- self._html5 = true;
2700
- self._webAudio = false;
2701
- self._sounds = [];
2702
- delete cache[url];
2703
- self.load();
2704
- }
2705
- };
2706
- safeXhrSend(xhr);
2707
- }
2708
- };
2709
-
2710
- /**
2711
- * Send the XHR request wrapped in a try/catch.
2712
- * @param {Object} xhr XHR to send.
2713
- */
2714
- var safeXhrSend = function(xhr) {
2715
- try {
2716
- xhr.send();
2717
- } catch (e) {
2718
- xhr.onerror();
2719
- }
2720
- };
2721
-
2722
- /**
2723
- * Decode audio data from an array buffer.
2724
- * @param {ArrayBuffer} arraybuffer The audio data.
2725
- * @param {Howl} self
2726
- */
2727
- var decodeAudioData = function(arraybuffer, self) {
2728
- // Fire a load error if something broke.
2729
- var error = function() {
2730
- self._emit('loaderror', null, 'Decoding audio data failed.');
2731
- };
2732
-
2733
- // Load the sound on success.
2734
- var success = function(buffer) {
2735
- if (buffer && self._sounds.length > 0) {
2736
- cache[self._src] = buffer;
2737
- loadSound(self, buffer);
2738
- } else {
2739
- error();
2740
- }
2741
- };
2742
-
2743
- // Decode the buffer into an audio source.
2744
- if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
2745
- Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
2746
- } else {
2747
- Howler.ctx.decodeAudioData(arraybuffer, success, error);
2748
- }
2749
- };
2750
-
2751
- /**
2752
- * Sound is now loaded, so finish setting everything up and fire the loaded event.
2753
- * @param {Howl} self
2754
- * @param {Object} buffer The decoded buffer sound source.
2755
- */
2756
- var loadSound = function(self, buffer) {
2757
- // Set the duration.
2758
- if (buffer && !self._duration) {
2759
- self._duration = buffer.duration;
2760
- }
2761
-
2762
- // Setup a sprite if none is defined.
2763
- if (Object.keys(self._sprite).length === 0) {
2764
- self._sprite = {__default: [0, self._duration * 1000]};
2765
- }
2766
-
2767
- // Fire the loaded event.
2768
- if (self._state !== 'loaded') {
2769
- self._state = 'loaded';
2770
- self._emit('load');
2771
- self._loadQueue();
2772
- }
2773
- };
2774
-
2775
- /**
2776
- * Setup the audio context when available, or switch to HTML5 Audio mode.
2777
- */
2778
- var setupAudioContext = function() {
2779
- // If we have already detected that Web Audio isn't supported, don't run this step again.
2780
- if (!Howler.usingWebAudio) {
2781
- return;
2782
- }
2783
-
2784
- // Check if we are using Web Audio and setup the AudioContext if we are.
2785
- try {
2786
- if (typeof AudioContext !== 'undefined') {
2787
- Howler.ctx = new AudioContext();
2788
- } else if (typeof webkitAudioContext !== 'undefined') {
2789
- Howler.ctx = new webkitAudioContext();
2790
- } else {
2791
- Howler.usingWebAudio = false;
2792
- }
2793
- } catch(e) {
2794
- Howler.usingWebAudio = false;
2795
- }
2796
-
2797
- // If the audio context creation still failed, set using web audio to false.
2798
- if (!Howler.ctx) {
2799
- Howler.usingWebAudio = false;
2800
- }
2801
-
2802
- // Check if a webview is being used on iOS8 or earlier (rather than the browser).
2803
- // If it is, disable Web Audio as it causes crashing.
2804
- var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
2805
- var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
2806
- var version = appVersion ? parseInt(appVersion[1], 10) : null;
2807
- if (iOS && version && version < 9) {
2808
- var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
2809
- if (Howler._navigator && !safari) {
2810
- Howler.usingWebAudio = false;
2811
- }
2812
- }
2813
-
2814
- // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
2815
- if (Howler.usingWebAudio) {
2816
- Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
2817
- Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : Howler._volume, Howler.ctx.currentTime);
2818
- Howler.masterGain.connect(Howler.ctx.destination);
2819
- }
2820
-
2821
- // Re-run the setup on Howler.
2822
- Howler._setup();
2823
- };
2824
-
2825
- // Add support for CommonJS libraries such as browserify.
2826
- {
2827
- exports.Howler = Howler;
2828
- exports.Howl = Howl;
2829
- }
2830
-
2831
- // Add to global in Node.js (for testing, etc).
2832
- if (typeof commonjsGlobal !== 'undefined') {
2833
- commonjsGlobal.HowlerGlobal = HowlerGlobal;
2834
- commonjsGlobal.Howler = Howler;
2835
- commonjsGlobal.Howl = Howl;
2836
- commonjsGlobal.Sound = Sound;
2837
- } else if (typeof window !== 'undefined') { // Define globally in case AMD is not available or unused.
2838
- window.HowlerGlobal = HowlerGlobal;
2839
- window.Howler = Howler;
2840
- window.Howl = Howl;
2841
- window.Sound = Sound;
2842
- }
2843
- })();
2844
-
2845
-
2846
- /*!
2847
- * Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported.
2848
- *
2849
- * howler.js v2.2.4
2850
- * howlerjs.com
2851
- *
2852
- * (c) 2013-2020, James Simpson of GoldFire Studios
2853
- * goldfirestudios.com
2854
- *
2855
- * MIT License
2856
- */
2857
-
2858
- (function() {
2859
-
2860
- // Setup default properties.
2861
- HowlerGlobal.prototype._pos = [0, 0, 0];
2862
- HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0];
2863
-
2864
- /** Global Methods **/
2865
- /***************************************************************************/
2866
-
2867
- /**
2868
- * Helper method to update the stereo panning position of all current Howls.
2869
- * Future Howls will not use this value unless explicitly set.
2870
- * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right.
2871
- * @return {Howler/Number} Self or current stereo panning value.
2872
- */
2873
- HowlerGlobal.prototype.stereo = function(pan) {
2874
- var self = this;
2875
-
2876
- // Stop right here if not using Web Audio.
2877
- if (!self.ctx || !self.ctx.listener) {
2878
- return self;
2879
- }
2880
-
2881
- // Loop through all Howls and update their stereo panning.
2882
- for (var i=self._howls.length-1; i>=0; i--) {
2883
- self._howls[i].stereo(pan);
2884
- }
2885
-
2886
- return self;
2887
- };
2888
-
2889
- /**
2890
- * Get/set the position of the listener in 3D cartesian space. Sounds using
2891
- * 3D position will be relative to the listener's position.
2892
- * @param {Number} x The x-position of the listener.
2893
- * @param {Number} y The y-position of the listener.
2894
- * @param {Number} z The z-position of the listener.
2895
- * @return {Howler/Array} Self or current listener position.
2896
- */
2897
- HowlerGlobal.prototype.pos = function(x, y, z) {
2898
- var self = this;
2899
-
2900
- // Stop right here if not using Web Audio.
2901
- if (!self.ctx || !self.ctx.listener) {
2902
- return self;
2903
- }
2904
-
2905
- // Set the defaults for optional 'y' & 'z'.
2906
- y = (typeof y !== 'number') ? self._pos[1] : y;
2907
- z = (typeof z !== 'number') ? self._pos[2] : z;
2908
-
2909
- if (typeof x === 'number') {
2910
- self._pos = [x, y, z];
2911
-
2912
- if (typeof self.ctx.listener.positionX !== 'undefined') {
2913
- self.ctx.listener.positionX.setTargetAtTime(self._pos[0], Howler.ctx.currentTime, 0.1);
2914
- self.ctx.listener.positionY.setTargetAtTime(self._pos[1], Howler.ctx.currentTime, 0.1);
2915
- self.ctx.listener.positionZ.setTargetAtTime(self._pos[2], Howler.ctx.currentTime, 0.1);
2916
- } else {
2917
- self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]);
2918
- }
2919
- } else {
2920
- return self._pos;
2921
- }
2922
-
2923
- return self;
2924
- };
2925
-
2926
- /**
2927
- * Get/set the direction the listener is pointing in the 3D cartesian space.
2928
- * A front and up vector must be provided. The front is the direction the
2929
- * face of the listener is pointing, and up is the direction the top of the
2930
- * listener is pointing. Thus, these values are expected to be at right angles
2931
- * from each other.
2932
- * @param {Number} x The x-orientation of the listener.
2933
- * @param {Number} y The y-orientation of the listener.
2934
- * @param {Number} z The z-orientation of the listener.
2935
- * @param {Number} xUp The x-orientation of the top of the listener.
2936
- * @param {Number} yUp The y-orientation of the top of the listener.
2937
- * @param {Number} zUp The z-orientation of the top of the listener.
2938
- * @return {Howler/Array} Returns self or the current orientation vectors.
2939
- */
2940
- HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) {
2941
- var self = this;
2942
-
2943
- // Stop right here if not using Web Audio.
2944
- if (!self.ctx || !self.ctx.listener) {
2945
- return self;
2946
- }
2947
-
2948
- // Set the defaults for optional 'y' & 'z'.
2949
- var or = self._orientation;
2950
- y = (typeof y !== 'number') ? or[1] : y;
2951
- z = (typeof z !== 'number') ? or[2] : z;
2952
- xUp = (typeof xUp !== 'number') ? or[3] : xUp;
2953
- yUp = (typeof yUp !== 'number') ? or[4] : yUp;
2954
- zUp = (typeof zUp !== 'number') ? or[5] : zUp;
2955
-
2956
- if (typeof x === 'number') {
2957
- self._orientation = [x, y, z, xUp, yUp, zUp];
2958
-
2959
- if (typeof self.ctx.listener.forwardX !== 'undefined') {
2960
- self.ctx.listener.forwardX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1);
2961
- self.ctx.listener.forwardY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1);
2962
- self.ctx.listener.forwardZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1);
2963
- self.ctx.listener.upX.setTargetAtTime(xUp, Howler.ctx.currentTime, 0.1);
2964
- self.ctx.listener.upY.setTargetAtTime(yUp, Howler.ctx.currentTime, 0.1);
2965
- self.ctx.listener.upZ.setTargetAtTime(zUp, Howler.ctx.currentTime, 0.1);
2966
- } else {
2967
- self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp);
2968
- }
2969
- } else {
2970
- return or;
2971
- }
2972
-
2973
- return self;
2974
- };
2975
-
2976
- /** Group Methods **/
2977
- /***************************************************************************/
2978
-
2979
- /**
2980
- * Add new properties to the core init.
2981
- * @param {Function} _super Core init method.
2982
- * @return {Howl}
2983
- */
2984
- Howl.prototype.init = (function(_super) {
2985
- return function(o) {
2986
- var self = this;
2987
-
2988
- // Setup user-defined default properties.
2989
- self._orientation = o.orientation || [1, 0, 0];
2990
- self._stereo = o.stereo || null;
2991
- self._pos = o.pos || null;
2992
- self._pannerAttr = {
2993
- coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360,
2994
- coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360,
2995
- coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0,
2996
- distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse',
2997
- maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000,
2998
- panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF',
2999
- refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1,
3000
- rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1
3001
- };
3002
-
3003
- // Setup event listeners.
3004
- self._onstereo = o.onstereo ? [{fn: o.onstereo}] : [];
3005
- self._onpos = o.onpos ? [{fn: o.onpos}] : [];
3006
- self._onorientation = o.onorientation ? [{fn: o.onorientation}] : [];
3007
-
3008
- // Complete initilization with howler.js core's init function.
3009
- return _super.call(this, o);
3010
- };
3011
- })(Howl.prototype.init);
3012
-
3013
- /**
3014
- * Get/set the stereo panning of the audio source for this sound or all in the group.
3015
- * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right.
3016
- * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
3017
- * @return {Howl/Number} Returns self or the current stereo panning value.
3018
- */
3019
- Howl.prototype.stereo = function(pan, id) {
3020
- var self = this;
3021
-
3022
- // Stop right here if not using Web Audio.
3023
- if (!self._webAudio) {
3024
- return self;
3025
- }
3026
-
3027
- // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable.
3028
- if (self._state !== 'loaded') {
3029
- self._queue.push({
3030
- event: 'stereo',
3031
- action: function() {
3032
- self.stereo(pan, id);
3033
- }
3034
- });
3035
-
3036
- return self;
3037
- }
3038
-
3039
- // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist.
3040
- var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo';
3041
-
3042
- // Setup the group's stereo panning if no ID is passed.
3043
- if (typeof id === 'undefined') {
3044
- // Return the group's stereo panning if no parameters are passed.
3045
- if (typeof pan === 'number') {
3046
- self._stereo = pan;
3047
- self._pos = [pan, 0, 0];
3048
- } else {
3049
- return self._stereo;
3050
- }
3051
- }
3052
-
3053
- // Change the streo panning of one or all sounds in group.
3054
- var ids = self._getSoundIds(id);
3055
- for (var i=0; i<ids.length; i++) {
3056
- // Get the sound.
3057
- var sound = self._soundById(ids[i]);
3058
-
3059
- if (sound) {
3060
- if (typeof pan === 'number') {
3061
- sound._stereo = pan;
3062
- sound._pos = [pan, 0, 0];
3063
-
3064
- if (sound._node) {
3065
- // If we are falling back, make sure the panningModel is equalpower.
3066
- sound._pannerAttr.panningModel = 'equalpower';
3067
-
3068
- // Check if there is a panner setup and create a new one if not.
3069
- if (!sound._panner || !sound._panner.pan) {
3070
- setupPanner(sound, pannerType);
3071
- }
3072
-
3073
- if (pannerType === 'spatial') {
3074
- if (typeof sound._panner.positionX !== 'undefined') {
3075
- sound._panner.positionX.setValueAtTime(pan, Howler.ctx.currentTime);
3076
- sound._panner.positionY.setValueAtTime(0, Howler.ctx.currentTime);
3077
- sound._panner.positionZ.setValueAtTime(0, Howler.ctx.currentTime);
3078
- } else {
3079
- sound._panner.setPosition(pan, 0, 0);
3080
- }
3081
- } else {
3082
- sound._panner.pan.setValueAtTime(pan, Howler.ctx.currentTime);
3083
- }
3084
- }
3085
-
3086
- self._emit('stereo', sound._id);
3087
- } else {
3088
- return sound._stereo;
3089
- }
3090
- }
3091
- }
3092
-
3093
- return self;
3094
- };
3095
-
3096
- /**
3097
- * Get/set the 3D spatial position of the audio source for this sound or group relative to the global listener.
3098
- * @param {Number} x The x-position of the audio source.
3099
- * @param {Number} y The y-position of the audio source.
3100
- * @param {Number} z The z-position of the audio source.
3101
- * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
3102
- * @return {Howl/Array} Returns self or the current 3D spatial position: [x, y, z].
3103
- */
3104
- Howl.prototype.pos = function(x, y, z, id) {
3105
- var self = this;
3106
-
3107
- // Stop right here if not using Web Audio.
3108
- if (!self._webAudio) {
3109
- return self;
3110
- }
3111
-
3112
- // If the sound hasn't loaded, add it to the load queue to change position when capable.
3113
- if (self._state !== 'loaded') {
3114
- self._queue.push({
3115
- event: 'pos',
3116
- action: function() {
3117
- self.pos(x, y, z, id);
3118
- }
3119
- });
3120
-
3121
- return self;
3122
- }
3123
-
3124
- // Set the defaults for optional 'y' & 'z'.
3125
- y = (typeof y !== 'number') ? 0 : y;
3126
- z = (typeof z !== 'number') ? -0.5 : z;
3127
-
3128
- // Setup the group's spatial position if no ID is passed.
3129
- if (typeof id === 'undefined') {
3130
- // Return the group's spatial position if no parameters are passed.
3131
- if (typeof x === 'number') {
3132
- self._pos = [x, y, z];
3133
- } else {
3134
- return self._pos;
3135
- }
3136
- }
3137
-
3138
- // Change the spatial position of one or all sounds in group.
3139
- var ids = self._getSoundIds(id);
3140
- for (var i=0; i<ids.length; i++) {
3141
- // Get the sound.
3142
- var sound = self._soundById(ids[i]);
3143
-
3144
- if (sound) {
3145
- if (typeof x === 'number') {
3146
- sound._pos = [x, y, z];
3147
-
3148
- if (sound._node) {
3149
- // Check if there is a panner setup and create a new one if not.
3150
- if (!sound._panner || sound._panner.pan) {
3151
- setupPanner(sound, 'spatial');
3152
- }
3153
-
3154
- if (typeof sound._panner.positionX !== 'undefined') {
3155
- sound._panner.positionX.setValueAtTime(x, Howler.ctx.currentTime);
3156
- sound._panner.positionY.setValueAtTime(y, Howler.ctx.currentTime);
3157
- sound._panner.positionZ.setValueAtTime(z, Howler.ctx.currentTime);
3158
- } else {
3159
- sound._panner.setPosition(x, y, z);
3160
- }
3161
- }
3162
-
3163
- self._emit('pos', sound._id);
3164
- } else {
3165
- return sound._pos;
3166
- }
3167
- }
3168
- }
3169
-
3170
- return self;
3171
- };
3172
-
3173
- /**
3174
- * Get/set the direction the audio source is pointing in the 3D cartesian coordinate
3175
- * space. Depending on how direction the sound is, based on the `cone` attributes,
3176
- * a sound pointing away from the listener can be quiet or silent.
3177
- * @param {Number} x The x-orientation of the source.
3178
- * @param {Number} y The y-orientation of the source.
3179
- * @param {Number} z The z-orientation of the source.
3180
- * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
3181
- * @return {Howl/Array} Returns self or the current 3D spatial orientation: [x, y, z].
3182
- */
3183
- Howl.prototype.orientation = function(x, y, z, id) {
3184
- var self = this;
3185
-
3186
- // Stop right here if not using Web Audio.
3187
- if (!self._webAudio) {
3188
- return self;
3189
- }
3190
-
3191
- // If the sound hasn't loaded, add it to the load queue to change orientation when capable.
3192
- if (self._state !== 'loaded') {
3193
- self._queue.push({
3194
- event: 'orientation',
3195
- action: function() {
3196
- self.orientation(x, y, z, id);
3197
- }
3198
- });
3199
-
3200
- return self;
3201
- }
3202
-
3203
- // Set the defaults for optional 'y' & 'z'.
3204
- y = (typeof y !== 'number') ? self._orientation[1] : y;
3205
- z = (typeof z !== 'number') ? self._orientation[2] : z;
3206
-
3207
- // Setup the group's spatial orientation if no ID is passed.
3208
- if (typeof id === 'undefined') {
3209
- // Return the group's spatial orientation if no parameters are passed.
3210
- if (typeof x === 'number') {
3211
- self._orientation = [x, y, z];
3212
- } else {
3213
- return self._orientation;
3214
- }
3215
- }
3216
-
3217
- // Change the spatial orientation of one or all sounds in group.
3218
- var ids = self._getSoundIds(id);
3219
- for (var i=0; i<ids.length; i++) {
3220
- // Get the sound.
3221
- var sound = self._soundById(ids[i]);
3222
-
3223
- if (sound) {
3224
- if (typeof x === 'number') {
3225
- sound._orientation = [x, y, z];
3226
-
3227
- if (sound._node) {
3228
- // Check if there is a panner setup and create a new one if not.
3229
- if (!sound._panner) {
3230
- // Make sure we have a position to setup the node with.
3231
- if (!sound._pos) {
3232
- sound._pos = self._pos || [0, 0, -0.5];
3233
- }
3234
-
3235
- setupPanner(sound, 'spatial');
3236
- }
3237
-
3238
- if (typeof sound._panner.orientationX !== 'undefined') {
3239
- sound._panner.orientationX.setValueAtTime(x, Howler.ctx.currentTime);
3240
- sound._panner.orientationY.setValueAtTime(y, Howler.ctx.currentTime);
3241
- sound._panner.orientationZ.setValueAtTime(z, Howler.ctx.currentTime);
3242
- } else {
3243
- sound._panner.setOrientation(x, y, z);
3244
- }
3245
- }
3246
-
3247
- self._emit('orientation', sound._id);
3248
- } else {
3249
- return sound._orientation;
3250
- }
3251
- }
3252
- }
3253
-
3254
- return self;
3255
- };
3256
-
3257
- /**
3258
- * Get/set the panner node's attributes for a sound or group of sounds.
3259
- * This method can optionall take 0, 1 or 2 arguments.
3260
- * pannerAttr() -> Returns the group's values.
3261
- * pannerAttr(id) -> Returns the sound id's values.
3262
- * pannerAttr(o) -> Set's the values of all sounds in this Howl group.
3263
- * pannerAttr(o, id) -> Set's the values of passed sound id.
3264
- *
3265
- * Attributes:
3266
- * coneInnerAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
3267
- * inside of which there will be no volume reduction.
3268
- * coneOuterAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
3269
- * outside of which the volume will be reduced to a constant value of `coneOuterGain`.
3270
- * coneOuterGain - (0 by default) A parameter for directional audio sources, this is the gain outside of the
3271
- * `coneOuterAngle`. It is a linear value in the range `[0, 1]`.
3272
- * distanceModel - ('inverse' by default) Determines algorithm used to reduce volume as audio moves away from
3273
- * listener. Can be `linear`, `inverse` or `exponential.
3274
- * maxDistance - (10000 by default) The maximum distance between source and listener, after which the volume
3275
- * will not be reduced any further.
3276
- * refDistance - (1 by default) A reference distance for reducing volume as source moves further from the listener.
3277
- * This is simply a variable of the distance model and has a different effect depending on which model
3278
- * is used and the scale of your coordinates. Generally, volume will be equal to 1 at this distance.
3279
- * rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. This is simply a
3280
- * variable of the distance model and can be in the range of `[0, 1]` with `linear` and `[0, ∞]`
3281
- * with `inverse` and `exponential`.
3282
- * panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio.
3283
- * Can be `HRTF` or `equalpower`.
3284
- *
3285
- * @return {Howl/Object} Returns self or current panner attributes.
3286
- */
3287
- Howl.prototype.pannerAttr = function() {
3288
- var self = this;
3289
- var args = arguments;
3290
- var o, id, sound;
3291
-
3292
- // Stop right here if not using Web Audio.
3293
- if (!self._webAudio) {
3294
- return self;
3295
- }
3296
-
3297
- // Determine the values based on arguments.
3298
- if (args.length === 0) {
3299
- // Return the group's panner attribute values.
3300
- return self._pannerAttr;
3301
- } else if (args.length === 1) {
3302
- if (typeof args[0] === 'object') {
3303
- o = args[0];
3304
-
3305
- // Set the grou's panner attribute values.
3306
- if (typeof id === 'undefined') {
3307
- if (!o.pannerAttr) {
3308
- o.pannerAttr = {
3309
- coneInnerAngle: o.coneInnerAngle,
3310
- coneOuterAngle: o.coneOuterAngle,
3311
- coneOuterGain: o.coneOuterGain,
3312
- distanceModel: o.distanceModel,
3313
- maxDistance: o.maxDistance,
3314
- refDistance: o.refDistance,
3315
- rolloffFactor: o.rolloffFactor,
3316
- panningModel: o.panningModel
3317
- };
3318
- }
3319
-
3320
- self._pannerAttr = {
3321
- coneInnerAngle: typeof o.pannerAttr.coneInnerAngle !== 'undefined' ? o.pannerAttr.coneInnerAngle : self._coneInnerAngle,
3322
- coneOuterAngle: typeof o.pannerAttr.coneOuterAngle !== 'undefined' ? o.pannerAttr.coneOuterAngle : self._coneOuterAngle,
3323
- coneOuterGain: typeof o.pannerAttr.coneOuterGain !== 'undefined' ? o.pannerAttr.coneOuterGain : self._coneOuterGain,
3324
- distanceModel: typeof o.pannerAttr.distanceModel !== 'undefined' ? o.pannerAttr.distanceModel : self._distanceModel,
3325
- maxDistance: typeof o.pannerAttr.maxDistance !== 'undefined' ? o.pannerAttr.maxDistance : self._maxDistance,
3326
- refDistance: typeof o.pannerAttr.refDistance !== 'undefined' ? o.pannerAttr.refDistance : self._refDistance,
3327
- rolloffFactor: typeof o.pannerAttr.rolloffFactor !== 'undefined' ? o.pannerAttr.rolloffFactor : self._rolloffFactor,
3328
- panningModel: typeof o.pannerAttr.panningModel !== 'undefined' ? o.pannerAttr.panningModel : self._panningModel
3329
- };
3330
- }
3331
- } else {
3332
- // Return this sound's panner attribute values.
3333
- sound = self._soundById(parseInt(args[0], 10));
3334
- return sound ? sound._pannerAttr : self._pannerAttr;
3335
- }
3336
- } else if (args.length === 2) {
3337
- o = args[0];
3338
- id = parseInt(args[1], 10);
3339
- }
3340
-
3341
- // Update the values of the specified sounds.
3342
- var ids = self._getSoundIds(id);
3343
- for (var i=0; i<ids.length; i++) {
3344
- sound = self._soundById(ids[i]);
3345
-
3346
- if (sound) {
3347
- // Merge the new values into the sound.
3348
- var pa = sound._pannerAttr;
3349
- pa = {
3350
- coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : pa.coneInnerAngle,
3351
- coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : pa.coneOuterAngle,
3352
- coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : pa.coneOuterGain,
3353
- distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : pa.distanceModel,
3354
- maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : pa.maxDistance,
3355
- refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : pa.refDistance,
3356
- rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : pa.rolloffFactor,
3357
- panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : pa.panningModel
3358
- };
3359
-
3360
- // Create a new panner node if one doesn't already exist.
3361
- var panner = sound._panner;
3362
- if (!panner) {
3363
- // Make sure we have a position to setup the node with.
3364
- if (!sound._pos) {
3365
- sound._pos = self._pos || [0, 0, -0.5];
3366
- }
3367
-
3368
- // Create a new panner node.
3369
- setupPanner(sound, 'spatial');
3370
- panner = sound._panner;
3371
- }
3372
-
3373
- // Update the panner values or create a new panner if none exists.
3374
- panner.coneInnerAngle = pa.coneInnerAngle;
3375
- panner.coneOuterAngle = pa.coneOuterAngle;
3376
- panner.coneOuterGain = pa.coneOuterGain;
3377
- panner.distanceModel = pa.distanceModel;
3378
- panner.maxDistance = pa.maxDistance;
3379
- panner.refDistance = pa.refDistance;
3380
- panner.rolloffFactor = pa.rolloffFactor;
3381
- panner.panningModel = pa.panningModel;
3382
- }
3383
- }
3384
-
3385
- return self;
3386
- };
3387
-
3388
- /** Single Sound Methods **/
3389
- /***************************************************************************/
3390
-
3391
- /**
3392
- * Add new properties to the core Sound init.
3393
- * @param {Function} _super Core Sound init method.
3394
- * @return {Sound}
3395
- */
3396
- Sound.prototype.init = (function(_super) {
3397
- return function() {
3398
- var self = this;
3399
- var parent = self._parent;
3400
-
3401
- // Setup user-defined default properties.
3402
- self._orientation = parent._orientation;
3403
- self._stereo = parent._stereo;
3404
- self._pos = parent._pos;
3405
- self._pannerAttr = parent._pannerAttr;
3406
-
3407
- // Complete initilization with howler.js core Sound's init function.
3408
- _super.call(this);
3409
-
3410
- // If a stereo or position was specified, set it up.
3411
- if (self._stereo) {
3412
- parent.stereo(self._stereo);
3413
- } else if (self._pos) {
3414
- parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
3415
- }
3416
- };
3417
- })(Sound.prototype.init);
3418
-
3419
- /**
3420
- * Override the Sound.reset method to clean up properties from the spatial plugin.
3421
- * @param {Function} _super Sound reset method.
3422
- * @return {Sound}
3423
- */
3424
- Sound.prototype.reset = (function(_super) {
3425
- return function() {
3426
- var self = this;
3427
- var parent = self._parent;
3428
-
3429
- // Reset all spatial plugin properties on this sound.
3430
- self._orientation = parent._orientation;
3431
- self._stereo = parent._stereo;
3432
- self._pos = parent._pos;
3433
- self._pannerAttr = parent._pannerAttr;
3434
-
3435
- // If a stereo or position was specified, set it up.
3436
- if (self._stereo) {
3437
- parent.stereo(self._stereo);
3438
- } else if (self._pos) {
3439
- parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id);
3440
- } else if (self._panner) {
3441
- // Disconnect the panner.
3442
- self._panner.disconnect(0);
3443
- self._panner = undefined;
3444
- parent._refreshBuffer(self);
3445
- }
3446
-
3447
- // Complete resetting of the sound.
3448
- return _super.call(this);
3449
- };
3450
- })(Sound.prototype.reset);
3451
-
3452
- /** Helper Methods **/
3453
- /***************************************************************************/
3454
-
3455
- /**
3456
- * Create a new panner node and save it on the sound.
3457
- * @param {Sound} sound Specific sound to setup panning on.
3458
- * @param {String} type Type of panner to create: 'stereo' or 'spatial'.
3459
- */
3460
- var setupPanner = function(sound, type) {
3461
- type = type || 'spatial';
3462
-
3463
- // Create the new panner node.
3464
- if (type === 'spatial') {
3465
- sound._panner = Howler.ctx.createPanner();
3466
- sound._panner.coneInnerAngle = sound._pannerAttr.coneInnerAngle;
3467
- sound._panner.coneOuterAngle = sound._pannerAttr.coneOuterAngle;
3468
- sound._panner.coneOuterGain = sound._pannerAttr.coneOuterGain;
3469
- sound._panner.distanceModel = sound._pannerAttr.distanceModel;
3470
- sound._panner.maxDistance = sound._pannerAttr.maxDistance;
3471
- sound._panner.refDistance = sound._pannerAttr.refDistance;
3472
- sound._panner.rolloffFactor = sound._pannerAttr.rolloffFactor;
3473
- sound._panner.panningModel = sound._pannerAttr.panningModel;
3474
-
3475
- if (typeof sound._panner.positionX !== 'undefined') {
3476
- sound._panner.positionX.setValueAtTime(sound._pos[0], Howler.ctx.currentTime);
3477
- sound._panner.positionY.setValueAtTime(sound._pos[1], Howler.ctx.currentTime);
3478
- sound._panner.positionZ.setValueAtTime(sound._pos[2], Howler.ctx.currentTime);
3479
- } else {
3480
- sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]);
3481
- }
3482
-
3483
- if (typeof sound._panner.orientationX !== 'undefined') {
3484
- sound._panner.orientationX.setValueAtTime(sound._orientation[0], Howler.ctx.currentTime);
3485
- sound._panner.orientationY.setValueAtTime(sound._orientation[1], Howler.ctx.currentTime);
3486
- sound._panner.orientationZ.setValueAtTime(sound._orientation[2], Howler.ctx.currentTime);
3487
- } else {
3488
- sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]);
3489
- }
3490
- } else {
3491
- sound._panner = Howler.ctx.createStereoPanner();
3492
- sound._panner.pan.setValueAtTime(sound._stereo, Howler.ctx.currentTime);
3493
- }
3494
-
3495
- sound._panner.connect(sound._node);
3496
-
3497
- // Update the connections.
3498
- if (!sound._paused) {
3499
- sound._parent.pause(sound._id, true).play(sound._id, true);
3500
- }
3501
- };
3502
- })();
3503
- } (howler));
47
+ type: Number,
48
+ default: 0
49
+ },
50
+ /**
51
+ * @description 段落切割符号
52
+ */
53
+ separators: {
54
+ type: Array,
55
+ default: () => [`
3504
56
 
3505
- Howler.autoUnlock = false;
3506
- const originalPlay = howler.Howl.prototype.play;
3507
- howler.Howl.prototype.play = function(soundId) {
3508
- const WeixinJSBridge = window.WeixinJSBridge;
3509
- WeixinJSBridge && WeixinJSBridge.invoke("getNetworkType", {}, () => {
3510
- if (!this.playing(soundId)) {
3511
- originalPlay.call(this, soundId);
3512
- }
3513
- }, false);
3514
- return originalPlay.call(this, soundId);
57
+ `, `
58
+ `]
59
+ },
60
+ /**
61
+ * @description 组件内会根据当前游标是否和 source 长度一致来判断,是否持续阅读, 当一致时,会关闭阅读状态。但若设置为 true,则会持续阅读, 这在动态接收数据时会有用
62
+ */
63
+ keepRead: {
64
+ type: Boolean,
65
+ default: !1
66
+ },
67
+ /**
68
+ * @description 是否使用自定义语音合成
69
+ */
70
+ textToSpeech: {
71
+ type: Function,
72
+ default: void 0
73
+ },
74
+ /**
75
+ * @description 段落处理函数
76
+ */
77
+ processing: {
78
+ type: Function,
79
+ default: L
80
+ },
81
+ status: {
82
+ type: String,
83
+ default: m.pending
84
+ },
85
+ paragraphMinlength: {
86
+ type: Number,
87
+ default: 20
88
+ },
89
+ /**
90
+ * @description 禁用, 即不产出段落
91
+ */
92
+ disabled: {
93
+ type: Boolean,
94
+ default: !1
95
+ }
96
+ }, N = {
97
+ setData: (e) => e,
98
+ "update:status": (e) => !0,
99
+ paragraphLoad: (e) => !0,
100
+ complete: () => !0
101
+ }, se = {
102
+ data: {
103
+ type: Object,
104
+ default: () => ({})
105
+ },
106
+ deferred: {
107
+ type: Object,
108
+ required: !0
109
+ },
110
+ render: {
111
+ type: Function,
112
+ default: C
113
+ }
114
+ }, oe = {
115
+ setData: (e) => e,
116
+ load: (e) => !0
117
+ }, $e = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
118
+ __proto__: null,
119
+ emits: N,
120
+ paragraphEmits: oe,
121
+ paragraphProps: se,
122
+ props: H
123
+ }, Symbol.toStringTag, { value: "Module" }));
124
+ Howler.autoUnlock = !1;
125
+ const E = M.prototype.play;
126
+ M.prototype.play = function(e) {
127
+ const n = window.WeixinJSBridge;
128
+ return n && n.invoke("getNetworkType", {}, () => {
129
+ this.playing(e) || E.call(this, e);
130
+ }, !1), E.call(this, e);
3515
131
  };
3516
- function useHowlerParagraph(props, emit) {
3517
- const sound = shallowRef(null);
3518
- const broadcast = computed({
3519
- get: () => props.status,
3520
- set: (val) => {
3521
- emit("update:status", val);
3522
- }
3523
- });
3524
- const createSound = (url2) => {
3525
- if (!url2)
3526
- return null;
3527
- if (sound.value) {
3528
- sound.value.unload();
3529
- }
3530
- return new howler.Howl({
3531
- src: [url2],
3532
- format: ["mp3", "wav", "aac"],
3533
- onplay: () => {
3534
- broadcast.value = TickerStatus.playing;
3535
- },
3536
- onpause: () => {
3537
- broadcast.value = TickerStatus.paused;
3538
- },
3539
- onend: () => {
3540
- broadcast.value = TickerStatus.stopped;
3541
- setTimeout(() => {
3542
- if (sound.value) {
3543
- sound.value.unload();
3544
- sound.value = null;
3545
- }
3546
- }, 400);
3547
- },
3548
- onstop: () => {
3549
- broadcast.value = TickerStatus.stopped;
3550
- },
3551
- onloaderror: (_, error) => {
3552
- broadcast.value = TickerStatus.failed;
3553
- emit("error", error);
3554
- },
3555
- onplayerror: (_, error) => {
3556
- broadcast.value = TickerStatus.failed;
3557
- emit("error", error);
3558
- }
3559
- });
3560
- };
3561
- const url = computed(() => props.source);
3562
- watch(() => url.value, (newUrl) => {
3563
- if (newUrl) {
3564
- sound.value = createSound(newUrl);
3565
- }
3566
- }, { immediate: true });
3567
- onBeforeUnmount(() => {
3568
- if (sound.value) {
3569
- sound.value.unload();
3570
- sound.value = null;
3571
- }
3572
- });
3573
- watchEffect(() => {
3574
- if (broadcast.value === Broadcast.play) {
3575
- if (sound.value) {
3576
- sound.value.play();
3577
- } else {
3578
- console.warn("warn: No sound instance available for play");
3579
- }
3580
- } else if (broadcast.value === Broadcast.pause) {
3581
- sound.value?.pause();
3582
- } else if (broadcast.value === Broadcast.stop) {
3583
- sound.value?.stop();
3584
- }
3585
- });
3586
- return {
3587
- url,
3588
- broadcast,
3589
- sound
132
+ function ue(e, n) {
133
+ const t = F(null), r = w({
134
+ get: () => e.status,
135
+ set: (c) => {
136
+ n("update:status", c);
137
+ }
138
+ }), u = (c) => c ? (t.value && t.value.unload(), new M({
139
+ src: [c],
140
+ format: ["mp3", "wav", "aac"],
141
+ onplay: () => {
142
+ r.value = m.playing;
143
+ },
144
+ onpause: () => {
145
+ r.value = m.paused;
146
+ },
147
+ onend: () => {
148
+ r.value = m.stopped, setTimeout(() => {
149
+ t.value && (t.value.unload(), t.value = null);
150
+ }, 400);
151
+ },
152
+ onstop: () => {
153
+ r.value = m.stopped;
154
+ },
155
+ onloaderror: (o, d) => {
156
+ r.value = m.failed, n("error", d);
157
+ },
158
+ onplayerror: (o, d) => {
159
+ r.value = m.failed, n("error", d);
160
+ }
161
+ })) : null, s = w(() => e.source);
162
+ return _(() => s.value, (c) => {
163
+ c && (t.value = u(c));
164
+ }, { immediate: !0 }), W(() => {
165
+ t.value && (t.value.unload(), t.value = null);
166
+ }), Q(() => {
167
+ r.value === y.play ? t.value ? t.value.play() : console.warn("warn: No sound instance available for play") : r.value === y.pause ? t.value?.pause() : r.value === y.stop && t.value?.stop();
168
+ }), {
169
+ url: s,
170
+ broadcast: r,
171
+ sound: t
3590
172
  };
3591
173
  }
3592
-
3593
- var _sfc_main$2 = /* @__PURE__ */ defineComponent({
174
+ const le = /* @__PURE__ */ B({
3594
175
  __name: "howler-speech",
3595
176
  props: {
3596
177
  /**
@@ -3602,884 +183,273 @@ var _sfc_main$2 = /* @__PURE__ */ defineComponent({
3602
183
  },
3603
184
  status: {
3604
185
  type: String,
3605
- default: TickerStatus.pending
186
+ default: m.pending
3606
187
  }
3607
188
  },
3608
189
  emits: {
3609
190
  "update:status": null,
3610
- "load": null,
3611
- "error": null
3612
- },
3613
- setup(__props, { expose: __expose, emit: __emit }) {
3614
- __expose();
3615
- const props = __props;
3616
- const emit = __emit;
3617
- if (!props.source) {
3618
- emit("update:status", TickerStatus.stopped);
3619
- } else {
3620
- useHowlerParagraph(props, emit);
3621
- }
3622
- onMounted(() => {
3623
- emit("load");
3624
- });
3625
- const __returned__ = { props, emit };
3626
- Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
3627
- return __returned__;
3628
- }
3629
- });
3630
-
3631
- function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) {
3632
- return renderSlot(_ctx.$slots, "default", { status: $props.status });
3633
- }
3634
- var HowlerSpeechView = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["render", _sfc_render$2], ["__file", "/home/runner/work/vunk-plus/vunk-plus/packages/components/broadcasting-markdown/src/howler-speech.vue"]]);
3635
-
3636
- const LogLevels = {
3637
- silent: Number.NEGATIVE_INFINITY,
3638
- fatal: 0,
3639
- error: 0,
3640
- warn: 1,
3641
- log: 2,
3642
- info: 3,
3643
- success: 3,
3644
- fail: 3,
3645
- ready: 3,
3646
- start: 3,
3647
- box: 3,
3648
- debug: 4,
3649
- trace: 5,
3650
- verbose: Number.POSITIVE_INFINITY
3651
- };
3652
- const LogTypes = {
3653
- // Silent
3654
- silent: {
3655
- level: -1
191
+ load: null,
192
+ error: null
3656
193
  },
3657
- // Level 0
3658
- fatal: {
3659
- level: LogLevels.fatal
3660
- },
3661
- error: {
3662
- level: LogLevels.error
3663
- },
3664
- // Level 1
3665
- warn: {
3666
- level: LogLevels.warn
3667
- },
3668
- // Level 2
3669
- log: {
3670
- level: LogLevels.log
3671
- },
3672
- // Level 3
3673
- info: {
3674
- level: LogLevels.info
3675
- },
3676
- success: {
3677
- level: LogLevels.success
3678
- },
3679
- fail: {
3680
- level: LogLevels.fail
3681
- },
3682
- ready: {
3683
- level: LogLevels.info
3684
- },
3685
- start: {
3686
- level: LogLevels.info
3687
- },
3688
- box: {
3689
- level: LogLevels.info
3690
- },
3691
- // Level 4
3692
- debug: {
3693
- level: LogLevels.debug
3694
- },
3695
- // Level 5
3696
- trace: {
3697
- level: LogLevels.trace
3698
- },
3699
- // Verbose
3700
- verbose: {
3701
- level: LogLevels.verbose
3702
- }
3703
- };
3704
-
3705
- function isObject(value) {
3706
- return value !== null && typeof value === "object";
3707
- }
3708
- function _defu(baseObject, defaults, namespace = ".", merger) {
3709
- if (!isObject(defaults)) {
3710
- return _defu(baseObject, {}, namespace);
3711
- }
3712
- const object = Object.assign({}, defaults);
3713
- for (const key in baseObject) {
3714
- if (key === "__proto__" || key === "constructor") {
3715
- continue;
3716
- }
3717
- const value = baseObject[key];
3718
- if (value === null || value === void 0) {
3719
- continue;
3720
- }
3721
- if (Array.isArray(value) && Array.isArray(object[key])) {
3722
- object[key] = [...value, ...object[key]];
3723
- } else if (isObject(value) && isObject(object[key])) {
3724
- object[key] = _defu(
3725
- value,
3726
- object[key],
3727
- (namespace ? `${namespace}.` : "") + key.toString());
3728
- } else {
3729
- object[key] = value;
3730
- }
3731
- }
3732
- return object;
3733
- }
3734
- function createDefu(merger) {
3735
- return (...arguments_) => (
3736
- // eslint-disable-next-line unicorn/no-array-reduce
3737
- arguments_.reduce((p, c) => _defu(p, c, ""), {})
3738
- );
3739
- }
3740
- const defu = createDefu();
3741
-
3742
- function isPlainObject(obj) {
3743
- return Object.prototype.toString.call(obj) === "[object Object]";
3744
- }
3745
- function isLogObj(arg) {
3746
- if (!isPlainObject(arg)) {
3747
- return false;
3748
- }
3749
- if (!arg.message && !arg.args) {
3750
- return false;
3751
- }
3752
- if (arg.stack) {
3753
- return false;
3754
- }
3755
- return true;
3756
- }
3757
-
3758
- let paused = false;
3759
- const queue = [];
3760
- class Consola {
3761
- constructor(options = {}) {
3762
- const types = options.types || LogTypes;
3763
- this.options = defu(
3764
- {
3765
- ...options,
3766
- defaults: { ...options.defaults },
3767
- level: _normalizeLogLevel(options.level, types),
3768
- reporters: [...options.reporters || []]
3769
- },
3770
- {
3771
- types: LogTypes,
3772
- throttle: 1e3,
3773
- throttleMin: 5,
3774
- formatOptions: {
3775
- date: true,
3776
- colors: false,
3777
- compact: true
3778
- }
3779
- }
3780
- );
3781
- for (const type in types) {
3782
- const defaults = {
3783
- type,
3784
- ...this.options.defaults,
3785
- ...types[type]
3786
- };
3787
- this[type] = this._wrapLogFn(defaults);
3788
- this[type].raw = this._wrapLogFn(
3789
- defaults,
3790
- true
3791
- );
3792
- }
3793
- if (this.options.mockFn) {
3794
- this.mockTypes();
3795
- }
3796
- this._lastLog = {};
3797
- }
3798
- get level() {
3799
- return this.options.level;
3800
- }
3801
- set level(level) {
3802
- this.options.level = _normalizeLogLevel(
3803
- level,
3804
- this.options.types,
3805
- this.options.level
3806
- );
3807
- }
3808
- prompt(message, opts) {
3809
- if (!this.options.prompt) {
3810
- throw new Error("prompt is not supported!");
3811
- }
3812
- return this.options.prompt(message, opts);
3813
- }
3814
- create(options) {
3815
- const instance = new Consola({
3816
- ...this.options,
3817
- ...options
3818
- });
3819
- if (this._mockFn) {
3820
- instance.mockTypes(this._mockFn);
3821
- }
3822
- return instance;
3823
- }
3824
- withDefaults(defaults) {
3825
- return this.create({
3826
- ...this.options,
3827
- defaults: {
3828
- ...this.options.defaults,
3829
- ...defaults
3830
- }
3831
- });
3832
- }
3833
- withTag(tag) {
3834
- return this.withDefaults({
3835
- tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag
3836
- });
194
+ setup(e, { emit: n }) {
195
+ const t = e, r = n;
196
+ return t.source ? ue(t, r) : r("update:status", m.stopped), x(() => {
197
+ r("load");
198
+ }), (u, s) => S(u.$slots, "default", { status: e.status });
3837
199
  }
3838
- addReporter(reporter) {
3839
- this.options.reporters.push(reporter);
3840
- return this;
3841
- }
3842
- removeReporter(reporter) {
3843
- if (reporter) {
3844
- const i = this.options.reporters.indexOf(reporter);
3845
- if (i >= 0) {
3846
- return this.options.reporters.splice(i, 1);
3847
- }
3848
- } else {
3849
- this.options.reporters.splice(0);
3850
- }
3851
- return this;
3852
- }
3853
- setReporters(reporters) {
3854
- this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
3855
- return this;
3856
- }
3857
- wrapAll() {
3858
- this.wrapConsole();
3859
- this.wrapStd();
3860
- }
3861
- restoreAll() {
3862
- this.restoreConsole();
3863
- this.restoreStd();
3864
- }
3865
- wrapConsole() {
3866
- for (const type in this.options.types) {
3867
- if (!console["__" + type]) {
3868
- console["__" + type] = console[type];
3869
- }
3870
- console[type] = this[type].raw;
3871
- }
3872
- }
3873
- restoreConsole() {
3874
- for (const type in this.options.types) {
3875
- if (console["__" + type]) {
3876
- console[type] = console["__" + type];
3877
- delete console["__" + type];
3878
- }
3879
- }
3880
- }
3881
- wrapStd() {
3882
- this._wrapStream(this.options.stdout, "log");
3883
- this._wrapStream(this.options.stderr, "log");
3884
- }
3885
- _wrapStream(stream, type) {
3886
- if (!stream) {
3887
- return;
3888
- }
3889
- if (!stream.__write) {
3890
- stream.__write = stream.write;
3891
- }
3892
- stream.write = (data) => {
3893
- this[type].raw(String(data).trim());
3894
- };
3895
- }
3896
- restoreStd() {
3897
- this._restoreStream(this.options.stdout);
3898
- this._restoreStream(this.options.stderr);
3899
- }
3900
- _restoreStream(stream) {
3901
- if (!stream) {
3902
- return;
3903
- }
3904
- if (stream.__write) {
3905
- stream.write = stream.__write;
3906
- delete stream.__write;
3907
- }
3908
- }
3909
- pauseLogs() {
3910
- paused = true;
3911
- }
3912
- resumeLogs() {
3913
- paused = false;
3914
- const _queue = queue.splice(0);
3915
- for (const item of _queue) {
3916
- item[0]._logFn(item[1], item[2]);
3917
- }
3918
- }
3919
- mockTypes(mockFn) {
3920
- const _mockFn = mockFn || this.options.mockFn;
3921
- this._mockFn = _mockFn;
3922
- if (typeof _mockFn !== "function") {
3923
- return;
3924
- }
3925
- for (const type in this.options.types) {
3926
- this[type] = _mockFn(type, this.options.types[type]) || this[type];
3927
- this[type].raw = this[type];
3928
- }
3929
- }
3930
- _wrapLogFn(defaults, isRaw) {
3931
- return (...args) => {
3932
- if (paused) {
3933
- queue.push([this, defaults, args, isRaw]);
3934
- return;
3935
- }
3936
- return this._logFn(defaults, args, isRaw);
3937
- };
3938
- }
3939
- _logFn(defaults, args, isRaw) {
3940
- if ((defaults.level || 0) > this.level) {
3941
- return false;
3942
- }
3943
- const logObj = {
3944
- date: /* @__PURE__ */ new Date(),
3945
- args: [],
3946
- ...defaults,
3947
- level: _normalizeLogLevel(defaults.level, this.options.types)
3948
- };
3949
- if (!isRaw && args.length === 1 && isLogObj(args[0])) {
3950
- Object.assign(logObj, args[0]);
3951
- } else {
3952
- logObj.args = [...args];
3953
- }
3954
- if (logObj.message) {
3955
- logObj.args.unshift(logObj.message);
3956
- delete logObj.message;
3957
- }
3958
- if (logObj.additional) {
3959
- if (!Array.isArray(logObj.additional)) {
3960
- logObj.additional = logObj.additional.split("\n");
3961
- }
3962
- logObj.args.push("\n" + logObj.additional.join("\n"));
3963
- delete logObj.additional;
3964
- }
3965
- logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
3966
- logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
3967
- const resolveLog = (newLog = false) => {
3968
- const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
3969
- if (this._lastLog.object && repeated > 0) {
3970
- const args2 = [...this._lastLog.object.args];
3971
- if (repeated > 1) {
3972
- args2.push(`(repeated ${repeated} times)`);
3973
- }
3974
- this._log({ ...this._lastLog.object, args: args2 });
3975
- this._lastLog.count = 1;
3976
- }
3977
- if (newLog) {
3978
- this._lastLog.object = logObj;
3979
- this._log(logObj);
3980
- }
3981
- };
3982
- clearTimeout(this._lastLog.timeout);
3983
- const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
3984
- this._lastLog.time = logObj.date;
3985
- if (diffTime < this.options.throttle) {
3986
- try {
3987
- const serializedLog = JSON.stringify([
3988
- logObj.type,
3989
- logObj.tag,
3990
- logObj.args
3991
- ]);
3992
- const isSameLog = this._lastLog.serialized === serializedLog;
3993
- this._lastLog.serialized = serializedLog;
3994
- if (isSameLog) {
3995
- this._lastLog.count = (this._lastLog.count || 0) + 1;
3996
- if (this._lastLog.count > this.options.throttleMin) {
3997
- this._lastLog.timeout = setTimeout(
3998
- resolveLog,
3999
- this.options.throttle
4000
- );
4001
- return;
4002
- }
4003
- }
4004
- } catch {
4005
- }
4006
- }
4007
- resolveLog(true);
4008
- }
4009
- _log(logObj) {
4010
- for (const reporter of this.options.reporters) {
4011
- reporter.log(logObj, {
4012
- options: this.options
4013
- });
4014
- }
4015
- }
4016
- }
4017
- function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
4018
- if (input === void 0) {
4019
- return defaultLevel;
4020
- }
4021
- if (typeof input === "number") {
4022
- return input;
4023
- }
4024
- if (types[input] && types[input].level !== void 0) {
4025
- return types[input].level;
4026
- }
4027
- return defaultLevel;
4028
- }
4029
- Consola.prototype.add = Consola.prototype.addReporter;
4030
- Consola.prototype.remove = Consola.prototype.removeReporter;
4031
- Consola.prototype.clear = Consola.prototype.removeReporter;
4032
- Consola.prototype.withScope = Consola.prototype.withTag;
4033
- Consola.prototype.mock = Consola.prototype.mockTypes;
4034
- Consola.prototype.pause = Consola.prototype.pauseLogs;
4035
- Consola.prototype.resume = Consola.prototype.resumeLogs;
4036
- function createConsola$1(options = {}) {
4037
- return new Consola(options);
4038
- }
4039
-
4040
- class BrowserReporter {
4041
- constructor(options) {
4042
- this.options = { ...options };
4043
- this.defaultColor = "#7f8c8d";
4044
- this.levelColorMap = {
4045
- 0: "#c0392b",
4046
- // Red
4047
- 1: "#f39c12",
4048
- // Yellow
4049
- 3: "#00BCD4"
4050
- // Cyan
4051
- };
4052
- this.typeColorMap = {
4053
- success: "#2ecc71"
4054
- // Green
4055
- };
4056
- }
4057
- _getLogFn(level) {
4058
- if (level < 1) {
4059
- return console.__error || console.error;
4060
- }
4061
- if (level === 1) {
4062
- return console.__warn || console.warn;
4063
- }
4064
- return console.__log || console.log;
4065
- }
4066
- log(logObj) {
4067
- const consoleLogFn = this._getLogFn(logObj.level);
4068
- const type = logObj.type === "log" ? "" : logObj.type;
4069
- const tag = logObj.tag || "";
4070
- const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor;
4071
- const style = `
4072
- background: ${color};
4073
- border-radius: 0.5em;
4074
- color: white;
4075
- font-weight: bold;
4076
- padding: 2px 0.5em;
4077
- `;
4078
- const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
4079
- if (typeof logObj.args[0] === "string") {
4080
- consoleLogFn(
4081
- `${badge}%c ${logObj.args[0]}`,
4082
- style,
4083
- // Empty string as style resets to default console style
4084
- "",
4085
- ...logObj.args.slice(1)
4086
- );
4087
- } else {
4088
- consoleLogFn(badge, style, ...logObj.args);
4089
- }
4090
- }
4091
- }
4092
-
4093
- function createConsola(options = {}) {
4094
- const consola2 = createConsola$1({
4095
- reporters: options.reporters || [new BrowserReporter({})],
4096
- prompt(message, options2 = {}) {
4097
- if (options2.type === "confirm") {
4098
- return Promise.resolve(confirm(message));
4099
- }
4100
- return Promise.resolve(prompt(message));
4101
- },
4102
- ...options
4103
- });
4104
- return consola2;
4105
- }
4106
- const consola = createConsola();
4107
-
4108
- var _sfc_main$1 = /* @__PURE__ */ defineComponent({
200
+ }), ie = /* @__PURE__ */ B({
4109
201
  __name: "paragraph",
4110
202
  props: {
4111
203
  enable: {
4112
204
  type: Boolean,
4113
- default: true
205
+ default: !0
4114
206
  },
4115
207
  status: {
4116
208
  type: String,
4117
- default: ParagraphStatus.initial
209
+ default: i.initial
4118
210
  },
4119
211
  processing: {
4120
212
  type: Function,
4121
- default: noop
213
+ default: L
4122
214
  }
4123
215
  },
4124
216
  emits: ["update:status"],
4125
- setup(__props, { expose: __expose, emit: __emit }) {
4126
- __expose();
4127
- const props = __props;
4128
- const emit = __emit;
4129
- const theDef = shallowRef();
4130
- const processingDef = useDeferred();
4131
- onMounted(async () => {
4132
- emit("update:status", ParagraphStatus.processing);
4133
- await props.processing?.();
4134
- processingDef.resolve();
4135
- });
4136
- processingDef.promise.catch(() => {
4137
- emit("update:status", ParagraphStatus.rejected);
4138
- });
4139
- watch(() => props.enable, async (enable) => {
4140
- if (enable) {
4141
- init();
4142
- } else {
4143
- theDef.value = void 0;
4144
- }
4145
- }, { immediate: true });
4146
- async function init() {
4147
- const deferred = new Deferred();
4148
- await processingDef.promise;
4149
- emit("update:status", ParagraphStatus.pending);
4150
- deferred.promise.then(() => {
4151
- emit("update:status", ParagraphStatus.fulfilled);
4152
- }).catch(async (err) => {
4153
- consola.error("error", err);
4154
- emit("update:status", ParagraphStatus.rejected);
4155
- });
4156
- theDef.value = void 0;
4157
- nextTick(() => {
4158
- theDef.value = deferred;
217
+ setup(e, { emit: n }) {
218
+ const t = e, r = n, u = F(), s = q();
219
+ x(async () => {
220
+ r("update:status", i.processing), await t.processing?.(), s.resolve();
221
+ }), s.promise.catch(() => {
222
+ r("update:status", i.rejected);
223
+ }), _(() => t.enable, async (o) => {
224
+ o ? c() : u.value = void 0;
225
+ }, { immediate: !0 });
226
+ async function c() {
227
+ const o = new te();
228
+ await s.promise, r("update:status", i.pending), o.promise.then(() => {
229
+ r("update:status", i.fulfilled);
230
+ }).catch(async (d) => {
231
+ ae.error("error", d), r("update:status", i.rejected);
232
+ }), u.value = void 0, G(() => {
233
+ u.value = o;
4159
234
  });
4160
235
  }
4161
- const __returned__ = { props, emit, theDef, processingDef, init };
4162
- Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
4163
- return __returned__;
236
+ return (o, d) => e.enable && u.value ? S(o.$slots, "default", {
237
+ key: 0,
238
+ deferred: u.value
239
+ }) : K("", !0);
4164
240
  }
4165
241
  });
4166
-
4167
- function _sfc_render$1(_ctx, _cache, $props, $setup, $data, $options) {
4168
- return $props.enable && $setup.theDef ? renderSlot(_ctx.$slots, "default", {
4169
- key: 0,
4170
- deferred: $setup.theDef
4171
- }) : createCommentVNode("v-if", true);
4172
- }
4173
- var ParagraphView = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["render", _sfc_render$1], ["__file", "/home/runner/work/vunk-plus/vunk-plus/packages/components/broadcasting-markdown/src/paragraph.vue"]]);
4174
-
4175
- function resolveSeparatorParagraphActions(options) {
242
+ function ce(e) {
4176
243
  const {
4177
- source,
4178
- currentIndex,
4179
- sortedSeparators,
4180
- paragraphMinlength,
4181
- lastParagraph
4182
- } = options;
4183
- const mergeActions = [];
4184
- const appendActions = [];
4185
- for (const separator of sortedSeparators) {
4186
- const separatorLen = separator.length;
4187
- const compareText = source.slice(
4188
- currentIndex - separatorLen,
4189
- currentIndex
4190
- );
4191
- if (compareText !== separator) {
4192
- continue;
4193
- }
4194
- const start = lastParagraph?.end ?? 0;
4195
- const end = currentIndex;
4196
- const value = source.slice(start, end);
4197
- if (lastParagraph && separator.length >= value.length) {
4198
- if (lastParagraph.status === ParagraphStatus.initial) {
4199
- mergeActions.push({
4200
- end,
4201
- value: source.slice(lastParagraph.start, end),
4202
- separator
4203
- });
4204
- }
244
+ source: n,
245
+ currentIndex: t,
246
+ sortedSeparators: r,
247
+ paragraphMinlength: u,
248
+ lastParagraph: s
249
+ } = e, c = [], o = [];
250
+ for (const d of r) {
251
+ const f = d.length;
252
+ if (n.slice(
253
+ t - f,
254
+ t
255
+ ) !== d)
4205
256
  continue;
4206
- }
4207
- if (value.length > paragraphMinlength) {
4208
- appendActions.push({
4209
- start,
4210
- separator,
4211
- end,
4212
- status: ParagraphStatus.initial,
4213
- value,
4214
- broadcast: Broadcast.play
257
+ const g = s?.end ?? 0, p = t, k = n.slice(g, p);
258
+ if (s && d.length >= k.length) {
259
+ s.status === i.initial && c.push({
260
+ end: p,
261
+ value: n.slice(s.start, p),
262
+ separator: d
4215
263
  });
264
+ continue;
4216
265
  }
266
+ k.length > u && o.push({
267
+ start: g,
268
+ separator: d,
269
+ end: p,
270
+ status: i.initial,
271
+ value: k,
272
+ broadcast: y.play
273
+ });
4217
274
  }
4218
275
  return {
4219
- mergeActions,
4220
- appendActions
276
+ mergeActions: c,
277
+ appendActions: o
4221
278
  };
4222
279
  }
4223
- function resolveTailParagraphAction(options) {
4224
- const { source, currentIndex, lastParagraph } = options;
4225
- if (lastParagraph?.end === currentIndex) {
280
+ function de(e) {
281
+ const { source: n, currentIndex: t, lastParagraph: r } = e;
282
+ if (r?.end === t)
4226
283
  return { type: "none" };
4227
- }
4228
- const start = lastParagraph?.end ?? 0;
4229
- const end = currentIndex;
4230
- if (lastParagraph && lastParagraph.status === ParagraphStatus.initial && lastParagraph.separator === "") {
4231
- return {
4232
- type: "merge",
4233
- data: {
4234
- end,
4235
- value: source.slice(lastParagraph.start, end),
4236
- separator: ""
4237
- }
4238
- };
4239
- }
4240
- return {
284
+ const u = r?.end ?? 0, s = t;
285
+ return r && r.status === i.initial && r.separator === "" ? {
286
+ type: "merge",
287
+ data: {
288
+ end: s,
289
+ value: n.slice(r.start, s),
290
+ separator: ""
291
+ }
292
+ } : {
4241
293
  type: "append",
4242
294
  data: {
4243
- start,
295
+ start: u,
4244
296
  separator: "",
4245
- end,
4246
- status: ParagraphStatus.initial,
4247
- value: source.slice(start, end),
4248
- broadcast: Broadcast.play
297
+ end: s,
298
+ status: i.initial,
299
+ value: n.slice(u, s),
300
+ broadcast: y.play
4249
301
  }
4250
302
  };
4251
303
  }
4252
-
4253
- var _sfc_main = defineComponent({
304
+ const pe = B({
4254
305
  name: "VkBroadcastingMarkdown",
4255
306
  components: {
4256
- ParagraphView,
4257
- HowlerSpeechView,
4258
- VkTypingMarkdown
307
+ ParagraphView: ie,
308
+ HowlerSpeechView: le,
309
+ VkTypingMarkdown: R
4259
310
  },
4260
- props,
4261
- emits,
4262
- setup(props2, { emit }) {
4263
- const [theData, handleSetData] = useDataComputed({
311
+ props: H,
312
+ emits: N,
313
+ setup(e, { emit: n }) {
314
+ const [t, r] = z({
4264
315
  default: []
4265
- }, props2, emit);
4266
- const queue = new AsyncQueue();
4267
- const addParagraph = (paragraph) => {
4268
- const k = theData.value.length;
4269
- if (k === 0) {
4270
- paragraph.broadcast = props2.status;
4271
- }
4272
- handleSetData({
4273
- k,
4274
- v: paragraph
316
+ }, e, n), u = new U(), s = (a) => {
317
+ const l = t.value.length;
318
+ l === 0 && (a.broadcast = e.status), r({
319
+ k: l,
320
+ v: a
4275
321
  });
4276
- };
4277
- const processingParagraph = async (paragraph) => {
4278
- if (!props2.textToSpeech) {
322
+ }, c = async (a) => {
323
+ if (!e.textToSpeech)
4279
324
  return;
4280
- }
4281
- const value = props2.render(paragraph.value);
4282
- if (props2.separators.includes(value)) {
4283
- return;
4284
- }
4285
- if (!value) {
325
+ const l = e.render(a.value);
326
+ if (e.separators.includes(l) || !l)
4286
327
  return;
4287
- }
4288
- const resPromise = props2.textToSpeech(value);
4289
- await queue.wait();
4290
- return resPromise.then(async (res) => {
4291
- if (res instanceof Blob) {
4292
- paragraph.blob = res;
4293
- paragraph.url = await blobToDataURL(res);
4294
- }
4295
- if (typeof res === "string") {
4296
- paragraph.url = res;
4297
- }
328
+ const v = e.textToSpeech(l);
329
+ return await u.wait(), v.then(async (h) => {
330
+ h instanceof Blob && (a.blob = h, a.url = await J(h)), typeof h == "string" && (a.url = h);
4298
331
  }).then(async () => {
4299
- await props2.processing?.(paragraph);
4300
- queue.shift();
4301
- });
4302
- };
4303
- const currentIndex = ref(0);
4304
- const isFinished = computed(() => {
4305
- return currentIndex.value >= props2.source.length;
4306
- });
4307
- const fulfilledTextValue = computed(() => {
4308
- if (props2.disabled) {
4309
- return props2.source;
4310
- }
4311
- return theData.value.filter(
4312
- (item) => item.status === ParagraphStatus.fulfilled || item.status === ParagraphStatus.pending
4313
- ).map((item) => item.value).join("");
4314
- });
4315
- const sortedSeparators = computed(() => {
4316
- return [...props2.separators].sort((a, b) => {
4317
- return a.length - b.length;
4318
- });
4319
- });
4320
- watch(isFinished, (val) => {
4321
- if (props2.disabled) {
4322
- return;
4323
- }
4324
- !val && write();
4325
- }, { immediate: true });
4326
- function write() {
4327
- const lastParagraph = theData.value.at(-1);
4328
- const separatorActions = resolveSeparatorParagraphActions({
4329
- source: props2.source,
4330
- currentIndex: currentIndex.value,
4331
- sortedSeparators: sortedSeparators.value,
4332
- paragraphMinlength: props2.paragraphMinlength,
4333
- lastParagraph
4334
- });
4335
- separatorActions.mergeActions.forEach((action) => {
4336
- if (!lastParagraph) {
4337
- return;
4338
- }
4339
- lastParagraph.end = action.end;
4340
- lastParagraph.value = action.value;
4341
- lastParagraph.separator = action.separator;
332
+ await e.processing?.(a), u.shift();
4342
333
  });
4343
- separatorActions.appendActions.forEach((action) => {
4344
- addParagraph(action);
334
+ }, o = X(0), d = w(() => o.value >= e.source.length), f = w(() => e.disabled ? e.source : t.value.filter(
335
+ (a) => a.status === i.fulfilled || a.status === i.pending
336
+ ).map((a) => a.value).join("")), b = w(() => [...e.separators].sort((a, l) => a.length - l.length));
337
+ _(d, (a) => {
338
+ e.disabled || !a && g();
339
+ }, { immediate: !0 });
340
+ function g() {
341
+ const a = t.value.at(-1), l = ce({
342
+ source: e.source,
343
+ currentIndex: o.value,
344
+ sortedSeparators: b.value,
345
+ paragraphMinlength: e.paragraphMinlength,
346
+ lastParagraph: a
4345
347
  });
4346
- if (currentIndex.value < props2.source.length) {
4347
- currentIndex.value++;
4348
- setTimeout(write, props2.delay);
4349
- } else {
4350
- if (props2.keepRead) {
4351
- setTimeout(write, props2.delay);
348
+ if (l.mergeActions.forEach((v) => {
349
+ a && (a.end = v.end, a.value = v.value, a.separator = v.separator);
350
+ }), l.appendActions.forEach((v) => {
351
+ s(v);
352
+ }), o.value < e.source.length)
353
+ o.value++, setTimeout(g, e.delay);
354
+ else {
355
+ if (e.keepRead) {
356
+ setTimeout(g, e.delay);
4352
357
  return;
4353
358
  }
4354
- const latestParagraph = theData.value.at(-1);
4355
- const tailAction = resolveTailParagraphAction({
4356
- source: props2.source,
4357
- currentIndex: currentIndex.value,
4358
- lastParagraph: latestParagraph
359
+ const v = t.value.at(-1), h = de({
360
+ source: e.source,
361
+ currentIndex: o.value,
362
+ lastParagraph: v
4359
363
  });
4360
- if (tailAction.type === "none") {
364
+ if (h.type === "none")
4361
365
  return;
4362
- }
4363
- if (tailAction.type === "merge") {
4364
- if (!latestParagraph) {
366
+ if (h.type === "merge") {
367
+ if (!v)
4365
368
  return;
4366
- }
4367
- latestParagraph.end = tailAction.data.end;
4368
- latestParagraph.value = tailAction.data.value;
4369
- latestParagraph.separator = tailAction.data.separator;
369
+ v.end = h.data.end, v.value = h.data.value, v.separator = h.data.separator;
4370
370
  return;
4371
371
  }
4372
- addParagraph(tailAction.data);
372
+ s(h.data);
4373
373
  }
4374
374
  }
4375
- function isPrevParagraphFulfilled(currentIndex2) {
4376
- const last = theData.value[currentIndex2 - 1];
4377
- return last ? last.status === ParagraphStatus.fulfilled : true;
375
+ function p(a) {
376
+ const l = t.value[a - 1];
377
+ return l ? l.status === i.fulfilled : !0;
4378
378
  }
4379
- function isParagraphEnabled(currentIndex2) {
4380
- const isPrevFulfilled = isPrevParagraphFulfilled(currentIndex2);
4381
- return isPrevFulfilled;
379
+ function k(a) {
380
+ return p(a);
4382
381
  }
4383
- const currentPragraph = computed(() => {
4384
- return theData.value.find((item) => item.status === ParagraphStatus.pending);
4385
- });
4386
- watch(() => props2.status, () => {
4387
- if (props2.status === TickerStatus.stop) {
4388
- theData.value.forEach((item) => {
4389
- if (item.broadcast !== TickerStatus.stopped) {
4390
- item.broadcast = Broadcast.stop;
4391
- }
4392
- });
4393
- }
4394
- if (!currentPragraph.value) {
4395
- return;
4396
- }
4397
- if (currentPragraph.value.broadcast !== props2.status) {
4398
- currentPragraph.value.broadcast = props2.status;
4399
- }
4400
- }, { immediate: true });
4401
- function handleParagraphStatus(para, v) {
4402
- if (para.status === ParagraphStatus.pending) {
4403
- emit("update:status", v);
4404
- }
382
+ const P = w(() => t.value.find((a) => a.status === i.pending));
383
+ _(() => e.status, () => {
384
+ e.status === m.stop && t.value.forEach((a) => {
385
+ a.broadcast !== m.stopped && (a.broadcast = y.stop);
386
+ }), P.value && P.value.broadcast !== e.status && (P.value.broadcast = e.status);
387
+ }, { immediate: !0 });
388
+ function O(a, l) {
389
+ a.status === i.pending && n("update:status", l);
4405
390
  }
4406
391
  return {
4407
- theData,
4408
- ParagraphStatus,
4409
- fulfilledTextValue,
4410
- processingParagraph,
4411
- setData,
4412
- Broadcast,
4413
- isParagraphEnabled,
4414
- TickerStatus,
4415
- handleParagraphStatus
392
+ theData: t,
393
+ ParagraphStatus: i,
394
+ fulfilledTextValue: f,
395
+ processingParagraph: c,
396
+ setData: I,
397
+ Broadcast: y,
398
+ isParagraphEnabled: k,
399
+ TickerStatus: m,
400
+ handleParagraphStatus: O
4416
401
  };
4417
402
  }
4418
403
  });
4419
-
4420
- function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
4421
- const _component_VkTypingMarkdown = resolveComponent("VkTypingMarkdown");
4422
- const _component_HowlerSpeechView = resolveComponent("HowlerSpeechView");
4423
- const _component_ParagraphView = resolveComponent("ParagraphView");
4424
- return openBlock(), createElementBlock(
4425
- Fragment,
4426
- null,
4427
- [
4428
- renderSlot(_ctx.$slots, "default", { paragraphs: _ctx.theData }, () => [
4429
- createVNode(_component_VkTypingMarkdown, { source: _ctx.fulfilledTextValue }, null, 8, ["source"])
404
+ function fe(e, n, t, r, u, s) {
405
+ const c = T("VkTypingMarkdown"), o = T("HowlerSpeechView"), d = T("ParagraphView");
406
+ return $(), D(j, null, [
407
+ S(e.$slots, "default", { paragraphs: e.theData }, () => [
408
+ A(c, { source: e.fulfilledTextValue }, null, 8, ["source"])
409
+ ]),
410
+ ($(!0), D(j, null, Y(e.theData, (f, b) => ($(), Z(d, {
411
+ key: f.value,
412
+ status: f.status,
413
+ "onUpdate:status": (g) => f.status = g,
414
+ enable: e.isParagraphEnabled(b),
415
+ processing: () => e.processingParagraph(f)
416
+ }, {
417
+ default: ee(({ deferred: g }) => [
418
+ S(e.$slots, "paragraph", {
419
+ data: f,
420
+ deferred: g
421
+ }, () => [
422
+ A(o, {
423
+ status: f.broadcast,
424
+ "onUpdate:status": [(p) => f.broadcast = p, (p) => {
425
+ e.handleParagraphStatus(f, p), p === e.TickerStatus.stopped && g.resolve(!0), b === e.theData.length - 1 && p === e.TickerStatus.stopped && e.$emit("complete");
426
+ }],
427
+ source: f.url,
428
+ onError: (p) => g.reject(p),
429
+ onLoad: (p) => e.$emit("paragraphLoad", {
430
+ data: f,
431
+ deferred: g
432
+ })
433
+ }, null, 8, ["status", "onUpdate:status", "source", "onError", "onLoad"])
434
+ ])
4430
435
  ]),
4431
- (openBlock(true), createElementBlock(
4432
- Fragment,
4433
- null,
4434
- renderList(_ctx.theData, (item, index) => {
4435
- return openBlock(), createBlock(_component_ParagraphView, {
4436
- key: item.value,
4437
- status: item.status,
4438
- "onUpdate:status": ($event) => item.status = $event,
4439
- enable: _ctx.isParagraphEnabled(index),
4440
- processing: () => _ctx.processingParagraph(item)
4441
- }, {
4442
- default: withCtx(({ deferred }) => [
4443
- renderSlot(_ctx.$slots, "paragraph", {
4444
- data: item,
4445
- deferred
4446
- }, () => [
4447
- createVNode(_component_HowlerSpeechView, {
4448
- status: item.broadcast,
4449
- "onUpdate:status": [($event) => item.broadcast = $event, (e) => {
4450
- _ctx.handleParagraphStatus(item, e);
4451
- e === _ctx.TickerStatus.stopped && deferred.resolve(true);
4452
- index === _ctx.theData.length - 1 && e === _ctx.TickerStatus.stopped && _ctx.$emit("complete");
4453
- }],
4454
- source: item.url,
4455
- onError: ($event) => deferred.reject($event),
4456
- onLoad: ($event) => _ctx.$emit("paragraphLoad", {
4457
- data: item,
4458
- deferred
4459
- })
4460
- }, null, 8, ["status", "onUpdate:status", "source", "onError", "onLoad"])
4461
- ])
4462
- ]),
4463
- _: 2
4464
- /* DYNAMIC */
4465
- }, 1032, ["status", "onUpdate:status", "enable", "processing"]);
4466
- }),
4467
- 128
4468
- /* KEYED_FRAGMENT */
4469
- ))
4470
- ],
4471
- 64
4472
- /* STABLE_FRAGMENT */
4473
- );
436
+ _: 2
437
+ }, 1032, ["status", "onUpdate:status", "enable", "processing"]))), 128))
438
+ ], 64);
4474
439
  }
4475
- var VkBroadcastingMarkdown = /* @__PURE__ */ _export_sfc(_sfc_main, [["render", _sfc_render], ["__file", "/home/runner/work/vunk-plus/vunk-plus/packages/components/broadcasting-markdown/src/index.vue"]]);
4476
-
4477
- var types = /*#__PURE__*/Object.freeze({
440
+ const V = /* @__PURE__ */ re(pe, [["render", fe]]), Ve = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4478
441
  __proto__: null
4479
- });
4480
-
4481
- VkBroadcastingMarkdown.install = (app) => {
4482
- app.component(VkBroadcastingMarkdown.name || "VkBroadcastingMarkdown", VkBroadcastingMarkdown);
442
+ }, Symbol.toStringTag, { value: "Module" }));
443
+ V.install = (e) => {
444
+ e.component(V.name || "VkBroadcastingMarkdown", V);
445
+ };
446
+ export {
447
+ y as Broadcast,
448
+ i as ParagraphStatus,
449
+ V as VkBroadcastingMarkdown,
450
+ $e as _VkBroadcastingMarkdownCtx,
451
+ Ve as __VkBroadcastingMarkdown,
452
+ V as default,
453
+ C as defaultRender,
454
+ ue as useHowlerParagraph
4483
455
  };
4484
-
4485
- export { Broadcast, ParagraphStatus, VkBroadcastingMarkdown, ctx as _VkBroadcastingMarkdownCtx, types as __VkBroadcastingMarkdown, VkBroadcastingMarkdown as default, defaultRender, useHowlerParagraph };