-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTTS.ts
57 lines (53 loc) · 1.62 KB
/
TTS.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { storageService } from "@/frontend/services/card-storage-service";
import { Card, CardType } from "@/common/interfaces/ConfigFile";
import { tts } from "./TTSServer";
export class TTS {
isPlaying = false;
audio = new Audio();
private static _instance: TTS;
static get instance (): TTS {
if (TTS._instance == null) {
TTS._instance = new TTS();
}
return TTS._instance;
}
public async playCards (file: string, cards: Card[], force = false) {
if (this.isPlaying) {
this.isPlaying = false;
this.audio.pause();
if (!force) return;
}
this.isPlaying = true;
for (const card of cards) {
if (!this.isPlaying) break;
if (card.cardType === CardType.AudioCard && card.audioPath) {
const buffer = await storageService.getAudio(file, card.audioPath);
if (!buffer) continue;
const url = URL.createObjectURL(
new Blob([buffer], { type: "audio/wav" } /* (1) */)
);
await this.playUrl(url);
}
}
this.isPlaying = false;
}
public async playText (text: string, voice = "alena"): Promise<void> {
if (this.isPlaying) { this.audio.pause(); return; }
this.isPlaying = true;
const buffer = await tts(text, voice);
const url = URL.createObjectURL(
new Blob([buffer], { type: "audio/wav" } /* (1) */)
);
await this.playUrl(url);
this.isPlaying = false;
}
private playUrl (url: string) {
return new Promise((resolve, reject) => {
this.audio.src = url;
this.audio.oncanplay = async () => {
await this.audio.play();
};
this.audio.onended = resolve;
});
}
}