markdown-up 5.2.2 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/voice.js ADDED
@@ -0,0 +1,825 @@
1
+ // Licensed under the MIT License
2
+ // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
+
4
+ // The MarkdownUp voice playback - text read aloud with PicoVox speech synthesis and Web Audio. The playback's text may
5
+ // grow as it plays (e.g., a response that's still generating): the text's last sentence is held back until the text is
6
+ // final, and if playback reaches the end of the text before it's final, it pauses. Apart from the playback, there are
7
+ // the voice lines - text said aloud in a voice and a speaking style (e.g., a film's dialogue), each over any others.
8
+
9
+ import {speechText, splitSentences} from 'picovox/lib/sentences.js';
10
+
11
+
12
+ // The voice playback sample rate (Hz) - PicoVox's own. The audio context runs at it, so the blocks join exactly.
13
+ const voiceSampleRate = 24000;
14
+
15
+
16
+ // The playback timing (s) - how far ahead of the audio context's time a block starts, and how far ahead of playback
17
+ // synthesis runs
18
+ const playbackLead = 0.05;
19
+ const playbackAhead = 4;
20
+
21
+
22
+ // The noise seed of the text's first sentence (sentence i is rendered with seed + i)
23
+ const playbackSeed = 1000;
24
+
25
+
26
+ // Skip back goes to the previous section within this many seconds of a section's start (otherwise, to the section's start)
27
+ const skipBackSeconds = 2;
28
+
29
+
30
+ // How long a voice line waits for its audio context to run (ms) - a line that can't be heard (the browser hasn't let the
31
+ // audio start) is dropped
32
+ const lineStartMs = 250;
33
+
34
+
35
+ // The voice playback speaking rates
36
+ export const voiceRates = [0.8, 1, 1.1, 1.2, 1.5];
37
+
38
+
39
+ // The default speaking style
40
+ const voiceDefaultStyle = 'neutral';
41
+
42
+
43
+ // The default male voice (the default voice) and the default female voice
44
+ const voiceDefaultMale = 'michael';
45
+ const voiceDefaultFemale = 'sarah';
46
+
47
+
48
+ // The voice label overrides - PicoVox's "male" and "female" voices are named
49
+ const voiceLabels = {'male': 'John', 'female': 'Mary'};
50
+
51
+
52
+ // The element model HTML tags that continue a paragraph's text
53
+ const inlineTags = new Set([
54
+ 'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i', 'ins', 'kbd', 'label', 'mark', 'q', 's',
55
+ 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'u', 'var'
56
+ ]);
57
+
58
+
59
+ // The element model HTML tags that aren't read aloud - code blocks, images, and controls
60
+ const skipTags = new Set([
61
+ 'audio', 'button', 'canvas', 'iframe', 'img', 'input', 'object', 'option', 'pre', 'script', 'select', 'style', 'textarea',
62
+ 'video'
63
+ ]);
64
+
65
+
66
+ // The element model HTML tags whose headers don't start a section
67
+ const nestedTags = new Set(['blockquote', 'li', 'td', 'th']);
68
+
69
+
70
+ // Matches a header tag
71
+ const rHeaderTag = /^h[1-6]$/;
72
+
73
+
74
+ // Matches text with something to read aloud - PicoVox speaks English text
75
+ const rSpeakable = /[A-Za-z0-9]/;
76
+
77
+
78
+ // Matches text that ends with punctuation (closing quotes and parentheses allowed)
79
+ const rTextEnd = /[.!?:;,]["')”’]*$/;
80
+
81
+
82
+ /**
83
+ * A paragraph of text to read aloud
84
+ *
85
+ * @typedef {Object} VoiceParagraph
86
+ * @property {string} text - The paragraph's text
87
+ * @property {boolean} section - If true, the paragraph starts a section (it's a top-level header)
88
+ *
89
+ * @ignore
90
+ */
91
+
92
+
93
+ /**
94
+ * Get an element model's paragraphs to read aloud. Code blocks, images, graphics, and controls are skipped. Each table
95
+ * row is a paragraph of its cells' texts as sentences. A header that isn't within a list, a block quote, or a table
96
+ * starts a section.
97
+ *
98
+ * @param {?(Object|Array)} elements - The element model
99
+ * @param {boolean} [skipNavigation = false] - If true, skip the paragraphs above the first section whose text is all
100
+ * links (e.g., a page's navigation links)
101
+ * @returns {Object[]} The array of [paragraphs]{@link module:lib/voice~VoiceParagraph}
102
+ *
103
+ * @ignore
104
+ */
105
+ export function voiceElementsParagraphs(elements, skipNavigation = false) {
106
+ const state = {'paragraphs': [], 'parts': [], 'linkOnly': true, 'section': false};
107
+ elementsParagraphs(state, elements, false, false);
108
+ paragraphEnd(state);
109
+
110
+ // Skip the link-only paragraphs above the first section?
111
+ const {paragraphs} = state;
112
+ const ixSection = (skipNavigation ? paragraphs.findIndex((paragraph) => paragraph.section) : -1);
113
+ return paragraphs.
114
+ filter((paragraph, ixParagraph) => !(ixParagraph < ixSection && paragraph.linkOnly)).
115
+ map(({text, section}) => ({text, section}));
116
+ }
117
+
118
+
119
+ // Helper to add an element model's text to its paragraphs
120
+ function elementsParagraphs(state, elements, inLink, nested) {
121
+ // Ignore non-objects
122
+ if (elements === null || typeof elements !== 'object') {
123
+ return;
124
+ }
125
+
126
+ // Array?
127
+ if (Array.isArray(elements)) {
128
+ for (const childElements of elements) {
129
+ elementsParagraphs(state, childElements, inLink, nested);
130
+ }
131
+ return;
132
+ }
133
+
134
+ // Text?
135
+ if ('text' in elements) {
136
+ const text = String(elements.text);
137
+ state.parts.push(text);
138
+ if (!inLink && rSpeakable.test(text)) {
139
+ state.linkOnly = false;
140
+ }
141
+ return;
142
+ }
143
+
144
+ // Graphics (and anything else that isn't HTML) aren't read aloud
145
+ if (typeof elements.html !== 'string') {
146
+ return;
147
+ }
148
+ const tag = elements.html.toLowerCase();
149
+ const elem = elements.elem ?? null;
150
+ const href = (elements.attr ?? null) !== null ? (elements.attr.href ?? null) : null;
151
+
152
+ // Code blocks, images, controls, and link buttons (links without a URL) aren't read aloud
153
+ if (skipTags.has(tag) || (tag === 'a' && href === null)) {
154
+ return;
155
+ }
156
+
157
+ // A line break is a space
158
+ if (tag === 'br') {
159
+ state.parts.push(' ');
160
+ return;
161
+ }
162
+
163
+ // Inline elements continue the paragraph
164
+ if (inlineTags.has(tag)) {
165
+ elementsParagraphs(state, elem, inLink || tag === 'a', nested);
166
+ return;
167
+ }
168
+
169
+ // A table cell is a sentence of its row's paragraph
170
+ if (tag === 'td' || tag === 'th') {
171
+ const ixCell = state.parts.length;
172
+ elementsParagraphs(state, elem, inLink, true);
173
+ const cellText = state.parts.slice(ixCell).join('').trim();
174
+ if (cellText !== '') {
175
+ state.parts.push(rTextEnd.test(cellText) ? ' ' : '. ');
176
+ }
177
+ return;
178
+ }
179
+
180
+ // Any other element is a paragraph (or contains paragraphs) - a top-level header starts a section
181
+ paragraphEnd(state);
182
+ elementsParagraphs(state, elem, inLink, nested || nestedTags.has(tag));
183
+ state.section = !nested && rHeaderTag.test(tag);
184
+ paragraphEnd(state);
185
+ }
186
+
187
+
188
+ // Helper to end the paragraph being added, if any
189
+ function paragraphEnd(state) {
190
+ const text = state.parts.join('').replace(/\s+/g, ' ').trim();
191
+ if (rSpeakable.test(text)) {
192
+ state.paragraphs.push({text, 'section': state.section, 'linkOnly': state.linkOnly});
193
+ }
194
+ state.parts = [];
195
+ state.linkOnly = true;
196
+ state.section = false;
197
+ }
198
+
199
+
200
+ // Load PicoVox - its synthesis module and its models - on first use
201
+ async function loadPicovox() {
202
+ const synthesis = await import('picovox/lib/synthesis.js');
203
+ const loadModel = synthesis.modelLoader(
204
+ () => import('picovox/lib/models/g2pModel.js'),
205
+ () => import('picovox/lib/models/voiceModel.js')
206
+ );
207
+ const model = await loadModel();
208
+ return {
209
+ 'voices': synthesis.voiceTable.map(({key, label, sex}) => ({key, label, sex})),
210
+ 'styles': synthesis.styleTable.map(({key}) => key),
211
+ 'paragraphPause': synthesis.paragraphPause,
212
+ 'sentencePause': synthesis.sentencePause,
213
+ 'sentenceBlocks': (text, options) => synthesis.sentenceBlocks(model, text, options)
214
+ };
215
+ }
216
+
217
+
218
+ // Get the voices in the playback's order - male and female interleaved, the default male voice first (the default
219
+ // voice), then the default female voice
220
+ function voicesInterleaved(voices) {
221
+ // Split the voices by sex, each with its default voice first
222
+ const defaults = [voiceDefaultMale, voiceDefaultFemale];
223
+ const ordered = [
224
+ ...defaults.flatMap((voiceKey) => voices.filter(({key}) => key === voiceKey)),
225
+ ...voices.filter(({key}) => !defaults.includes(key))
226
+ ];
227
+ const females = ordered.filter(({sex}) => sex === 'female');
228
+ const males = ordered.filter(({sex}) => sex !== 'female');
229
+
230
+ // Interleave the male and female voices
231
+ const interleaved = [];
232
+ for (let ixVoice = 0; ixVoice < males.length || ixVoice < females.length; ixVoice++) {
233
+ interleaved.push(...males.slice(ixVoice, ixVoice + 1), ...females.slice(ixVoice, ixVoice + 1));
234
+ }
235
+ return interleaved;
236
+ }
237
+
238
+
239
+ // The paragraphs' sentences to speak - until the text is final, its last sentence may be incomplete, so it's held back
240
+ function playbackSentences(paragraphs, final) {
241
+ const sentences = [];
242
+ for (const paragraph of paragraphs) {
243
+ let sectionStart = paragraph.section;
244
+ for (const {text, paragraphStart} of splitSentences(paragraph.text)) {
245
+ sentences.push({text, paragraphStart, sectionStart});
246
+ sectionStart = false;
247
+ }
248
+ }
249
+ return final ? sentences : sentences.slice(0, -1);
250
+ }
251
+
252
+
253
+ // The pause before a sentence (s) - none before the first sentence played, so that speech starts at once
254
+ function sentencePause(picovox, sentence, isFirst) {
255
+ if (isFirst) {
256
+ return 0;
257
+ }
258
+ return sentence.paragraphStart ? picovox.paragraphPause : picovox.sentencePause;
259
+ }
260
+
261
+
262
+ // A sentence's words, for comparing sentences - a sentence's punctuation may change as its text grows (e.g., Markdown
263
+ // emphasis spanning sentences is literal until it's closed)
264
+ function sentenceWords(sentence) {
265
+ return sentence.text.replace(/[^\p{L}\p{N}]+/gu, '');
266
+ }
267
+
268
+
269
+ // The sentence indexes that skip back and skip forward move to - the sections' first sentences (the text's first
270
+ // sentence starts one) or, if the text isn't in sections, the paragraphs' first sentences
271
+ function skipStarts(sentences) {
272
+ const sectionStarts = sentences.flatMap(({sectionStart}, ixSentence) => (ixSentence === 0 || sectionStart ? [ixSentence] : []));
273
+ if (sectionStarts.length > 1) {
274
+ return sectionStarts;
275
+ }
276
+ return sentences.flatMap(({paragraphStart}, ixSentence) => (paragraphStart ? [ixSentence] : []));
277
+ }
278
+
279
+
280
+ // Create a voice audio context. Where the browser has audio sessions (Safari), the page's audio is first declared
281
+ // playback audio (like a podcast's) - Web Audio is otherwise ambient audio, which an iPhone in silent mode mutes on its
282
+ // speaker.
283
+ function createAudioContext(window) {
284
+ const audioSession = (window.navigator ?? {}).audioSession ?? null;
285
+ if (audioSession !== null) {
286
+ audioSession.type = 'playback';
287
+ }
288
+ return new window.AudioContext({'sampleRate': voiceSampleRate});
289
+ }
290
+
291
+
292
+ // The next task - a promise resolved by a message to the page itself (a timer would be throttled in background tabs)
293
+ function nextTask() {
294
+ return new Promise((resolve) => {
295
+ const channel = new MessageChannel();
296
+ channel.port1.onmessage = () => {
297
+ channel.port1.close();
298
+ resolve();
299
+ };
300
+ channel.port2.postMessage(null);
301
+ });
302
+ }
303
+
304
+
305
+ // Wait for a run's event - a scheduled block ending, the text changing, or the run stopping
306
+ function runWait(run) {
307
+ return new Promise((resolve) => {
308
+ run.waiting.push(resolve);
309
+ });
310
+ }
311
+
312
+
313
+ // Wake a run's waiters
314
+ function runWake(run) {
315
+ for (const resolve of run.waiting.splice(0)) {
316
+ resolve();
317
+ }
318
+ }
319
+
320
+
321
+ /**
322
+ * The MarkdownUp voice playback - at most one playback at a time
323
+ *
324
+ * @property {Object} window - The web browser window object
325
+ * @property {function} onChange - The playback change callback, called when the playback's state changes
326
+ * @property {?string} voice - The preferred voice key (null is the default voice)
327
+ * @property {number} rate - The speaking rate, from 0.5 to 2 (1 is normal)
328
+ *
329
+ * @ignore
330
+ */
331
+ export class MarkdownUpVoice {
332
+ /**
333
+ * @param {Object} window - The web browser window object
334
+ * @param {function} onChange - The playback change callback, called when the playback's state changes
335
+ */
336
+ constructor(window, onChange) {
337
+ this.window = window;
338
+ this.onChange = onChange;
339
+ this.voice = null;
340
+ this.rate = 1;
341
+
342
+ // PicoVox, loaded on first use - {voices, styles, paragraphPause, sentencePause, sentenceBlocks}
343
+ this.loadFn = loadPicovox;
344
+ this.loading = null;
345
+ this.picovox = null;
346
+ this.voicesOrdered = null;
347
+
348
+ // The audio context, created on first playback (from a user gesture, so the browser lets the audio start)
349
+ this.audioContext = null;
350
+
351
+ // The playback, if any - {key, final, sentences, position (the sentence index to play from), playing,
352
+ // run (the active synthesis run, or null)}
353
+ this.playback = null;
354
+
355
+ // The voice lines that are playing - each {sources, done, stopped} - and their audio context (the playback's is
356
+ // suspended when the playback is paused), created on first use
357
+ this.lines = new Set();
358
+ this.lineAudioContext = null;
359
+ }
360
+
361
+
362
+ // Load PicoVox, once - a failed load is retried on the next call
363
+ load() {
364
+ if (this.loading === null) {
365
+ this.loading = this.loadFn().then((picovox) => {
366
+ this.picovox = picovox;
367
+ this.voicesOrdered = voicesInterleaved(picovox.voices);
368
+ this.onChange();
369
+ return picovox;
370
+ });
371
+ this.loading.catch(() => {
372
+ this.loading = null;
373
+ });
374
+ }
375
+ return this.loading;
376
+ }
377
+
378
+
379
+ // Get the playback's voice key - the preferred voice, if it's a voice (it's unknown until PicoVox loads)
380
+ voiceKey() {
381
+ const {voice, voicesOrdered} = this;
382
+ if (voicesOrdered === null) {
383
+ return voice ?? voiceDefaultMale;
384
+ }
385
+ return (voicesOrdered.find(({key}) => key === voice) ?? voicesOrdered[0]).key;
386
+ }
387
+
388
+
389
+ // Get the playback's voice label
390
+ voiceLabel() {
391
+ const voiceKey = this.voiceKey();
392
+ const voiceInfo = (this.voicesOrdered ?? []).find(({key}) => key === voiceKey) ?? null;
393
+ const voiceLabel = (voiceInfo !== null ? voiceInfo.label : `${voiceKey.slice(0, 1).toUpperCase()}${voiceKey.slice(1)}`);
394
+ return voiceLabels[voiceKey] ?? voiceLabel;
395
+ }
396
+
397
+
398
+ // Get the voice key after the playback's voice (wraps to the first voice) - null until PicoVox loads
399
+ voiceNext() {
400
+ const {voicesOrdered} = this;
401
+ if (voicesOrdered === null) {
402
+ return null;
403
+ }
404
+ const voiceKey = this.voiceKey();
405
+ const ixVoice = voicesOrdered.findIndex(({key}) => key === voiceKey);
406
+ return voicesOrdered[(ixVoice + 1) % voicesOrdered.length].key;
407
+ }
408
+
409
+
410
+ // Get the speaking rate after the playback's rate (wraps to the first rate)
411
+ rateNext() {
412
+ return voiceRates[(voiceRates.indexOf(this.rate) + 1) % voiceRates.length];
413
+ }
414
+
415
+
416
+ // Get the playback state - {key, playing} - or null if there's no playback
417
+ state() {
418
+ const {playback} = this;
419
+ return playback !== null ? {'key': playback.key, 'playing': playback.playing} : null;
420
+ }
421
+
422
+
423
+ // Start reading paragraphs aloud (from a user gesture, so the browser lets the audio start), closing any playback
424
+ speak(paragraphs, final, key) {
425
+ this.runStop();
426
+ if (this.audioContext === null) {
427
+ this.audioContext = createAudioContext(this.window);
428
+ }
429
+ this.audioContext.resume();
430
+ this.playback = {key, final, 'sentences': playbackSentences(paragraphs, final), 'position': 0, 'playing': true, 'run': null};
431
+ this.runStart();
432
+ this.onChange();
433
+ }
434
+
435
+
436
+ // Set the playback's paragraphs - its text grows as it plays (if the words that have already played change, the
437
+ // playback starts again from the beginning)
438
+ setText(paragraphs, final) {
439
+ const {playback} = this;
440
+ if (playback === null) {
441
+ return;
442
+ }
443
+
444
+ // Has the text that's already played changed? Has the text that's scheduled to play?
445
+ const {run} = playback;
446
+ const sentences = playbackSentences(paragraphs, final);
447
+ const ixSentence = this.playbackSentence();
448
+ const isChanged = (ix) => ix >= sentences.length || sentenceWords(sentences[ix]) !== sentenceWords(playback.sentences[ix]);
449
+ let playedChanged = false;
450
+ for (let ix = 0; ix < ixSentence && !playedChanged; ix++) {
451
+ playedChanged = isChanged(ix);
452
+ }
453
+ const scheduledChanged = run !== null && run.starts.some(([ixStarted]) => ixStarted >= ixSentence && isChanged(ixStarted));
454
+
455
+ // Update the text - if the text that's already played changed, start again from the beginning; if the text
456
+ // that's scheduled to play changed, continue from the sentence that's playing
457
+ playback.final = final;
458
+ playback.sentences = sentences;
459
+ if (playedChanged) {
460
+ this.playbackSeek(0);
461
+ } else if (scheduledChanged) {
462
+ this.playbackSeek(ixSentence);
463
+ } else if (run !== null) {
464
+ runWake(run);
465
+ }
466
+ }
467
+
468
+
469
+ // Close the playback, if any
470
+ close() {
471
+ if (this.playback !== null) {
472
+ this.runStop();
473
+ this.playback = null;
474
+ this.audioContext.suspend();
475
+ this.onChange();
476
+ }
477
+ }
478
+
479
+
480
+ // Play (resume) the playback
481
+ play() {
482
+ const {playback} = this;
483
+ if (playback !== null && !playback.playing) {
484
+ playback.playing = true;
485
+ this.audioContext.resume();
486
+ if (playback.run === null) {
487
+ this.runStart();
488
+ }
489
+ this.onChange();
490
+ }
491
+ }
492
+
493
+
494
+ // Pause the playback
495
+ pause() {
496
+ const {playback} = this;
497
+ if (playback !== null && playback.playing) {
498
+ playback.playing = false;
499
+ this.audioContext.suspend();
500
+ this.onChange();
501
+ }
502
+ }
503
+
504
+
505
+ // Move the playback back to the beginning
506
+ rewind() {
507
+ if (this.playback !== null) {
508
+ this.playbackSeek(0);
509
+ }
510
+ }
511
+
512
+
513
+ // Move the playback back to the start of the section - or, near the section's start, to the start of the previous
514
+ // section
515
+ skipBack() {
516
+ const {playback} = this;
517
+ if (playback === null || playback.sentences.length === 0) {
518
+ return;
519
+ }
520
+ const {sentences, run} = playback;
521
+ const starts = skipStarts(sentences);
522
+ const ixSentence = this.playbackSentence();
523
+
524
+ // Past the end of the text? Back to the start of the last section.
525
+ if (ixSentence >= sentences.length) {
526
+ this.playbackSeek(starts[starts.length - 1]);
527
+ return;
528
+ }
529
+
530
+ // Near the start of the section? Back to the start of the previous section.
531
+ const ixStart = starts.findLastIndex((start) => start <= ixSentence);
532
+ const start = starts[ixStart];
533
+ const startTime = run !== null ? (run.starts.find(([ixStarted]) => ixStarted === start) ?? [])[1] : undefined;
534
+ const isNearStart = ixSentence === start &&
535
+ (startTime === undefined || this.audioContext.currentTime - startTime < skipBackSeconds);
536
+ this.playbackSeek(isNearStart && ixStart > 0 ? starts[ixStart - 1] : start);
537
+ }
538
+
539
+
540
+ // Move the playback forward to the start of the next section, if there is one
541
+ skipForward() {
542
+ const {playback} = this;
543
+ if (playback === null) {
544
+ return;
545
+ }
546
+ const ixSentence = this.playbackSentence();
547
+ const ixNext = skipStarts(playback.sentences).find((start) => start > ixSentence);
548
+ if (ixNext !== undefined) {
549
+ this.playbackSeek(ixNext);
550
+ }
551
+ }
552
+
553
+
554
+ // Set the voice - the playback, if any, continues with it
555
+ setVoice(voice) {
556
+ if (voice !== this.voice) {
557
+ this.voice = voice;
558
+ if (this.playback !== null) {
559
+ this.playbackSeek(this.playbackSentence());
560
+ }
561
+ this.onChange();
562
+ }
563
+ }
564
+
565
+
566
+ // Set the speaking rate - the playback, if any, continues at it
567
+ setRate(rate) {
568
+ if (rate !== this.rate) {
569
+ this.rate = rate;
570
+ if (this.playback !== null) {
571
+ this.playbackSeek(this.playbackSentence());
572
+ }
573
+ this.onChange();
574
+ }
575
+ }
576
+
577
+
578
+ // Get the voice lines' audio context, creating (and starting) it on first use. A browser may not let audio start
579
+ // until the user interacts with the page, so the context is resumed when they do.
580
+ lineContext() {
581
+ if (this.lineAudioContext === null) {
582
+ const audioContext = createAudioContext(this.window);
583
+ this.lineAudioContext = audioContext;
584
+ const resume = () => {
585
+ if (audioContext.state !== 'running') {
586
+ audioContext.resume();
587
+ }
588
+ };
589
+ resume();
590
+ for (const eventType of ['pointerdown', 'pointerup', 'keydown']) {
591
+ this.window.addEventListener(eventType, resume);
592
+ }
593
+ }
594
+ return this.lineAudioContext;
595
+ }
596
+
597
+
598
+ // Prepare for voice lines (and voice playback) - load PicoVox and start the voice lines' audio context - so that
599
+ // the first line starts at once
600
+ prepare() {
601
+ this.lineContext();
602
+ this.load().catch(() => null);
603
+ }
604
+
605
+
606
+ // Test whether voice lines can be heard - the browser has let their audio start
607
+ ready() {
608
+ return this.lineContext().state === 'running';
609
+ }
610
+
611
+
612
+ // Say a line of text aloud, over any other lines - in a voice (null is the default voice), a speaking style, and
613
+ // at a speaking rate. An unknown voice is the default voice and an unknown style is the default style.
614
+ say(text, voice, style, rate) {
615
+ const line = {'sources': new Set(), 'done': false, 'stopped': false};
616
+ this.lines.add(line);
617
+ this.linePlay(line, this.lineContext(), text, voice, style, rate).catch((error) => {
618
+ this.window.console.error(`MarkdownUp: Voice line failed: ${error}`);
619
+ }).then(() => {
620
+ // The line ends when its audio does
621
+ line.done = true;
622
+ if (line.sources.size === 0) {
623
+ this.lines.delete(line);
624
+ }
625
+ });
626
+ }
627
+
628
+
629
+ // Stop the voice lines
630
+ sayStop() {
631
+ for (const line of this.lines) {
632
+ line.stopped = true;
633
+ for (const source of line.sources) {
634
+ source.onended = null;
635
+ source.stop();
636
+ }
637
+ line.sources.clear();
638
+ }
639
+ this.lines.clear();
640
+ }
641
+
642
+
643
+ // Synthesize and schedule a voice line's sentences, a block at a time (yielding to the page after each)
644
+ async linePlay(line, audioContext, text, voice, style, rate) {
645
+ // Wait for the audio context to run - a line that can't be heard is dropped
646
+ const picovox = await this.load();
647
+ await Promise.race([
648
+ audioContext.resume(),
649
+ new Promise((resolve) => {
650
+ this.window.setTimeout(resolve, lineStartMs);
651
+ })
652
+ ]);
653
+ if (line.stopped || audioContext.state !== 'running') {
654
+ return;
655
+ }
656
+
657
+ // Synthesize and schedule the sentences' blocks
658
+ const {voicesOrdered} = this;
659
+ const blockOptions = {
660
+ 'voice': (voicesOrdered.find(({key}) => key === voice) ?? voicesOrdered[0]).key,
661
+ 'style': picovox.styles.includes(style) ? style : voiceDefaultStyle,
662
+ rate,
663
+ 'sampleRate': voiceSampleRate
664
+ };
665
+ let time = 0;
666
+ for (const [ixSentence, sentence] of splitSentences(text).entries()) {
667
+ blockOptions.seed = playbackSeed + ixSentence;
668
+ blockOptions.pause = sentencePause(picovox, sentence, ixSentence === 0);
669
+ for (const block of picovox.sentenceBlocks(speechText(sentence.text), {...blockOptions})) {
670
+ if (line.stopped) {
671
+ return;
672
+ }
673
+ const buffer = audioContext.createBuffer(1, block.length, voiceSampleRate);
674
+ buffer.copyToChannel(block, 0);
675
+ const source = audioContext.createBufferSource();
676
+ source.buffer = buffer;
677
+ source.connect(audioContext.destination);
678
+ source.onended = () => {
679
+ line.sources.delete(source);
680
+ if (line.done && line.sources.size === 0) {
681
+ this.lines.delete(line);
682
+ }
683
+ };
684
+ time = Math.max(time, audioContext.currentTime + playbackLead);
685
+ line.sources.add(source);
686
+ source.start(time);
687
+ time += block.length / voiceSampleRate;
688
+ await nextTask();
689
+ }
690
+ }
691
+ }
692
+
693
+
694
+ // The index of the sentence that's playing (or that's next to play)
695
+ playbackSentence() {
696
+ const {run, position} = this.playback;
697
+ if (run === null) {
698
+ return position;
699
+ }
700
+ let sentence = run.position;
701
+ for (const [ixSentence, startTime] of run.starts) {
702
+ if (startTime <= this.audioContext.currentTime) {
703
+ sentence = ixSentence;
704
+ }
705
+ }
706
+ return sentence;
707
+ }
708
+
709
+
710
+ // Move the playback to a sentence - playing from there if it's playing, otherwise when it plays
711
+ playbackSeek(position) {
712
+ this.runStop();
713
+ this.playback.position = position;
714
+ if (this.playback.playing) {
715
+ this.runStart();
716
+ }
717
+ }
718
+
719
+
720
+ // Start a synthesis run at the playback's position
721
+ runStart() {
722
+ const {playback} = this;
723
+ const run = {'position': playback.position, 'starts': [], 'sources': new Set(), 'waiting': [], 'stopped': false};
724
+ playback.run = run;
725
+ this.runPlay(playback, run).catch((error) => {
726
+ // Synthesis failed - stop the playback
727
+ if (!run.stopped) {
728
+ this.window.console.error(`MarkdownUp: Voice playback failed: ${error}`);
729
+ this.runStop();
730
+ playback.playing = false;
731
+ this.audioContext.suspend();
732
+ this.onChange();
733
+ }
734
+ });
735
+ }
736
+
737
+
738
+ // Stop the playback's synthesis run, if any
739
+ runStop() {
740
+ const run = this.playback !== null ? this.playback.run : null;
741
+ if (run !== null) {
742
+ run.stopped = true;
743
+ for (const source of run.sources) {
744
+ source.onended = null;
745
+ source.stop();
746
+ }
747
+ run.sources.clear();
748
+ runWake(run);
749
+ this.playback.run = null;
750
+ }
751
+ }
752
+
753
+
754
+ // Synthesize and schedule the playback's sentences, a block at a time (yielding to the page after each), staying at
755
+ // most a few seconds ahead of playback
756
+ async runPlay(playback, run) {
757
+ const {audioContext} = this;
758
+ const picovox = await this.load();
759
+ let time = 0;
760
+ let ixSentence = run.position;
761
+ while (!run.stopped) {
762
+ // Wait for the sentence's text - while its earlier audio plays, or for the first sentence of the run
763
+ while (!run.stopped && ixSentence >= playback.sentences.length && !playback.final &&
764
+ (run.sources.size > 0 || run.starts.length === 0)) {
765
+ await runWait(run);
766
+ }
767
+ if (run.stopped || ixSentence >= playback.sentences.length) {
768
+ break;
769
+ }
770
+
771
+ // Synthesize and schedule the sentence's blocks
772
+ const sentence = playback.sentences[ixSentence];
773
+ const blockOptions = {
774
+ 'voice': this.voiceKey(),
775
+ 'rate': this.rate,
776
+ 'seed': playbackSeed + ixSentence,
777
+ 'pause': sentencePause(picovox, sentence, ixSentence === run.position),
778
+ 'sampleRate': voiceSampleRate
779
+ };
780
+ let isFirstBlock = true;
781
+ for (const block of picovox.sentenceBlocks(speechText(sentence.text), blockOptions)) {
782
+ if (run.stopped) {
783
+ return;
784
+ }
785
+ const buffer = audioContext.createBuffer(1, block.length, voiceSampleRate);
786
+ buffer.copyToChannel(block, 0);
787
+ const source = audioContext.createBufferSource();
788
+ source.buffer = buffer;
789
+ source.connect(audioContext.destination);
790
+ source.onended = () => {
791
+ run.sources.delete(source);
792
+ runWake(run);
793
+ };
794
+ time = Math.max(time, audioContext.currentTime + playbackLead);
795
+ if (isFirstBlock) {
796
+ run.starts.push([ixSentence, time]);
797
+ isFirstBlock = false;
798
+ }
799
+ run.sources.add(source);
800
+ source.start(time);
801
+ time += block.length / voiceSampleRate;
802
+ await nextTask();
803
+ while (!run.stopped && time - audioContext.currentTime > playbackAhead) {
804
+ await runWait(run);
805
+ }
806
+ }
807
+ ixSentence += 1;
808
+ }
809
+
810
+ // Wait for the scheduled audio to end
811
+ while (!run.stopped && run.sources.size > 0) {
812
+ await runWait(run);
813
+ }
814
+ if (run.stopped) {
815
+ return;
816
+ }
817
+
818
+ // The end of the text - if it's final, the playback ends (back at the start); otherwise, it pauses
819
+ playback.run = null;
820
+ playback.position = (playback.final ? 0 : ixSentence);
821
+ playback.playing = false;
822
+ audioContext.suspend();
823
+ this.onChange();
824
+ }
825
+ }