@charivo/tts 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Zeikar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # @charivo/tts
2
+
3
+ Stateful TTS manager for Charivo.
4
+
5
+ This package coordinates a `TTSPlayer`, audio playback lifecycle, and lip-sync
6
+ events. It works with browser-native speech, remote TTS APIs, and direct OpenAI
7
+ players.
8
+
9
+ Concrete players should declare `playbackMode` (`"audio"` or `"web-speech"`)
10
+ and can optionally declare `audioMimeType` so the manager does not need to rely
11
+ on constructor-name inference.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pnpm add @charivo/tts
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import { createTTSManager } from "@charivo/tts";
23
+ import { createRemoteTTSPlayer } from "@charivo/tts/remote";
24
+
25
+ const ttsManager = createTTSManager(
26
+ createRemoteTTSPlayer({ apiEndpoint: "/api/tts" }),
27
+ );
28
+
29
+ await ttsManager.speak("Hello", { voice: "marin" });
30
+ ```
31
+
32
+ ## Exports
33
+
34
+ - `createTTSManager(player)`
35
+ - `WebSpeechLipSyncSimulator`
36
+ - `getTTSPlaybackMode(player)`
37
+ - `getTTSAudioMimeType(player)`
38
+ - `supportsGenerateAudio(player)`
39
+
40
+ ## Event Bridge
41
+
42
+ `TTSManager` accepts an emit-only event bridge through `setEventEmitter(...)`.
43
+ It emits TTS lifecycle and lip-sync events back into core, but it does not
44
+ subscribe to upstream Charivo events.
45
+
46
+ When connected, the manager emits:
47
+
48
+ - `tts:audio:start`
49
+ - `tts:lipsync:update`
50
+ - `tts:audio:end`
@@ -0,0 +1,60 @@
1
+ import { TTSPlayer, TTSManager, CharivoEventEmitter, TTSPlaybackMode, TTSOptions } from '@charivo/core';
2
+
3
+ /**
4
+ * TTS Manager 생성 헬퍼 함수
5
+ */
6
+ declare function createTTSManager(ttsPlayer: TTSPlayer): TTSManager;
7
+
8
+ /**
9
+ * Web Speech Lip Sync Simulator
10
+ *
11
+ * Web Speech API용 텍스트 기반 립싱크 시뮬레이션
12
+ * 단어의 모음 개수와 길이를 기반으로 입 움직임을 시뮬레이션
13
+ */
14
+ declare class WebSpeechLipSyncSimulator {
15
+ private intervals;
16
+ private eventEmitter?;
17
+ constructor(eventEmitter?: CharivoEventEmitter);
18
+ /**
19
+ * 텍스트 기반 립싱크 시뮬레이션 시작
20
+ */
21
+ startSimulation(text: string, rate?: number): void;
22
+ /**
23
+ * 페이드 아웃 효과 생성
24
+ */
25
+ private createFadeEffect;
26
+ /**
27
+ * 시뮬레이션 중지
28
+ */
29
+ stopSimulation(): void;
30
+ /**
31
+ * 인터벌 정리
32
+ */
33
+ private clearIntervals;
34
+ /**
35
+ * 리소스 정리
36
+ */
37
+ dispose(): void;
38
+ }
39
+
40
+ /**
41
+ * TTS Player Capability Utilities
42
+ */
43
+
44
+ /**
45
+ * Resolve the playback mode used by the manager. Concrete players should
46
+ * provide `playbackMode`. The default fallback is `"audio"`.
47
+ */
48
+ declare function getTTSPlaybackMode(player: TTSPlayer): TTSPlaybackMode;
49
+ /**
50
+ * Resolve the MIME type used when generated audio is wrapped in a Blob.
51
+ */
52
+ declare function getTTSAudioMimeType(player: TTSPlayer): string;
53
+ /**
54
+ * TTS Player가 generateAudio 메서드를 지원하는지 확인
55
+ */
56
+ declare function supportsGenerateAudio(player: TTSPlayer): player is TTSPlayer & {
57
+ generateAudio(text: string, options?: TTSOptions): Promise<ArrayBuffer>;
58
+ };
59
+
60
+ export { WebSpeechLipSyncSimulator, createTTSManager, getTTSAudioMimeType, getTTSPlaybackMode, supportsGenerateAudio };
@@ -0,0 +1,60 @@
1
+ import { TTSPlayer, TTSManager, CharivoEventEmitter, TTSPlaybackMode, TTSOptions } from '@charivo/core';
2
+
3
+ /**
4
+ * TTS Manager 생성 헬퍼 함수
5
+ */
6
+ declare function createTTSManager(ttsPlayer: TTSPlayer): TTSManager;
7
+
8
+ /**
9
+ * Web Speech Lip Sync Simulator
10
+ *
11
+ * Web Speech API용 텍스트 기반 립싱크 시뮬레이션
12
+ * 단어의 모음 개수와 길이를 기반으로 입 움직임을 시뮬레이션
13
+ */
14
+ declare class WebSpeechLipSyncSimulator {
15
+ private intervals;
16
+ private eventEmitter?;
17
+ constructor(eventEmitter?: CharivoEventEmitter);
18
+ /**
19
+ * 텍스트 기반 립싱크 시뮬레이션 시작
20
+ */
21
+ startSimulation(text: string, rate?: number): void;
22
+ /**
23
+ * 페이드 아웃 효과 생성
24
+ */
25
+ private createFadeEffect;
26
+ /**
27
+ * 시뮬레이션 중지
28
+ */
29
+ stopSimulation(): void;
30
+ /**
31
+ * 인터벌 정리
32
+ */
33
+ private clearIntervals;
34
+ /**
35
+ * 리소스 정리
36
+ */
37
+ dispose(): void;
38
+ }
39
+
40
+ /**
41
+ * TTS Player Capability Utilities
42
+ */
43
+
44
+ /**
45
+ * Resolve the playback mode used by the manager. Concrete players should
46
+ * provide `playbackMode`. The default fallback is `"audio"`.
47
+ */
48
+ declare function getTTSPlaybackMode(player: TTSPlayer): TTSPlaybackMode;
49
+ /**
50
+ * Resolve the MIME type used when generated audio is wrapped in a Blob.
51
+ */
52
+ declare function getTTSAudioMimeType(player: TTSPlayer): string;
53
+ /**
54
+ * TTS Player가 generateAudio 메서드를 지원하는지 확인
55
+ */
56
+ declare function supportsGenerateAudio(player: TTSPlayer): player is TTSPlayer & {
57
+ generateAudio(text: string, options?: TTSOptions): Promise<ArrayBuffer>;
58
+ };
59
+
60
+ export { WebSpeechLipSyncSimulator, createTTSManager, getTTSAudioMimeType, getTTSPlaybackMode, supportsGenerateAudio };
package/dist/index.js ADDED
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ WebSpeechLipSyncSimulator: () => WebSpeechLipSyncSimulator,
24
+ createTTSManager: () => createTTSManager,
25
+ getTTSAudioMimeType: () => getTTSAudioMimeType,
26
+ getTTSPlaybackMode: () => getTTSPlaybackMode,
27
+ supportsGenerateAudio: () => supportsGenerateAudio
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+
31
+ // src/web-speech-lipsync-simulator.ts
32
+ var WebSpeechLipSyncSimulator = class {
33
+ intervals = [];
34
+ eventEmitter;
35
+ constructor(eventEmitter) {
36
+ this.eventEmitter = eventEmitter;
37
+ }
38
+ /**
39
+ * 텍스트 기반 립싱크 시뮬레이션 시작
40
+ */
41
+ startSimulation(text, rate = 1) {
42
+ this.clearIntervals();
43
+ if (!this.eventEmitter) return;
44
+ const words = text.split(/\s+/);
45
+ const baseInterval = 120 / rate;
46
+ let currentTime = 0;
47
+ words.forEach((word) => {
48
+ const intervalId = window.setTimeout(() => {
49
+ const vowels = (word.match(/[aeiouAEIOU]/g) || []).length;
50
+ const intensity = Math.min(0.3 + vowels * 0.15, 1);
51
+ this.eventEmitter?.emit("tts:lipsync:update", { rms: intensity });
52
+ this.createFadeEffect(intensity, baseInterval);
53
+ }, currentTime);
54
+ this.intervals.push(intervalId);
55
+ currentTime += baseInterval + word.length * 20 / rate;
56
+ });
57
+ }
58
+ /**
59
+ * 페이드 아웃 효과 생성
60
+ */
61
+ createFadeEffect(intensity, duration) {
62
+ const fadeSteps = 3;
63
+ for (let step = 1; step <= fadeSteps; step++) {
64
+ const fadeId = window.setTimeout(
65
+ () => {
66
+ const fadedIntensity = intensity * (1 - step / fadeSteps);
67
+ this.eventEmitter?.emit("tts:lipsync:update", {
68
+ rms: fadedIntensity
69
+ });
70
+ },
71
+ duration * step / fadeSteps
72
+ );
73
+ this.intervals.push(fadeId);
74
+ }
75
+ }
76
+ /**
77
+ * 시뮬레이션 중지
78
+ */
79
+ stopSimulation() {
80
+ this.clearIntervals();
81
+ if (this.eventEmitter) {
82
+ this.eventEmitter.emit("tts:lipsync:update", { rms: 0 });
83
+ }
84
+ }
85
+ /**
86
+ * 인터벌 정리
87
+ */
88
+ clearIntervals() {
89
+ this.intervals.forEach((id) => clearTimeout(id));
90
+ this.intervals = [];
91
+ }
92
+ /**
93
+ * 리소스 정리
94
+ */
95
+ dispose() {
96
+ this.stopSimulation();
97
+ }
98
+ };
99
+
100
+ // src/tts-utils.ts
101
+ function getTTSPlaybackMode(player) {
102
+ return player.playbackMode || "audio";
103
+ }
104
+ function getTTSAudioMimeType(player) {
105
+ return player.audioMimeType || "audio/wav";
106
+ }
107
+ function supportsGenerateAudio(player) {
108
+ return typeof player.generateAudio === "function";
109
+ }
110
+
111
+ // src/tts-manager.ts
112
+ var TTSManagerImpl = class {
113
+ ttsPlayer;
114
+ eventEmitter;
115
+ currentAudio = null;
116
+ currentAudioUrl = null;
117
+ playbackMode;
118
+ isAudioSessionActive = false;
119
+ // Web Speech 립싱크 시뮬레이션만 필요
120
+ webSimulator;
121
+ constructor(ttsPlayer) {
122
+ this.ttsPlayer = ttsPlayer;
123
+ this.playbackMode = getTTSPlaybackMode(ttsPlayer);
124
+ this.webSimulator = new WebSpeechLipSyncSimulator();
125
+ }
126
+ /**
127
+ * 이벤트 발신자 설정
128
+ */
129
+ setEventEmitter(eventEmitter) {
130
+ this.eventEmitter = eventEmitter;
131
+ this.webSimulator = new WebSpeechLipSyncSimulator(eventEmitter);
132
+ }
133
+ /**
134
+ * 텍스트 음성 변환 및 재생
135
+ */
136
+ async speak(text, options) {
137
+ await this.stop();
138
+ if (this.playbackMode === "web-speech") {
139
+ return this.handleWebSpeech(text, options);
140
+ } else {
141
+ return this.handleAudioSpeech(text, options);
142
+ }
143
+ }
144
+ /**
145
+ * 현재 재생 중인 음성 중지
146
+ */
147
+ async stop() {
148
+ this.webSimulator.stopSimulation();
149
+ try {
150
+ await this.ttsPlayer.stop();
151
+ } catch (error) {
152
+ console.warn("\u26A0\uFE0F TTS Manager: Failed to stop player cleanly", error);
153
+ }
154
+ if (this.currentAudio) {
155
+ this.currentAudio.onended = null;
156
+ this.currentAudio.onerror = null;
157
+ this.currentAudio.pause();
158
+ this.currentAudio = null;
159
+ }
160
+ if (this.currentAudioUrl) {
161
+ URL.revokeObjectURL(this.currentAudioUrl);
162
+ this.currentAudioUrl = null;
163
+ }
164
+ this.endAudioSession();
165
+ }
166
+ /**
167
+ * 음성 설정
168
+ */
169
+ setVoice(voice) {
170
+ this.ttsPlayer.setVoice(voice);
171
+ }
172
+ /**
173
+ * 지원 여부 확인
174
+ */
175
+ isSupported() {
176
+ return this.ttsPlayer.isSupported();
177
+ }
178
+ /**
179
+ * Web Speech API 처리 (시뮬레이션 립싱크)
180
+ */
181
+ async handleWebSpeech(text, options) {
182
+ const dummyAudio = document.createElement("audio");
183
+ dummyAudio.preload = "none";
184
+ this.startAudioSession(dummyAudio);
185
+ this.webSimulator.startSimulation(text, options?.rate || 1);
186
+ try {
187
+ await this.ttsPlayer.speak(text, options);
188
+ } finally {
189
+ this.webSimulator.stopSimulation();
190
+ this.endAudioSession();
191
+ }
192
+ }
193
+ /**
194
+ * Audio-based TTS 처리 (실시간 오디오 분석)
195
+ */
196
+ async handleAudioSpeech(text, options) {
197
+ if (supportsGenerateAudio(this.ttsPlayer)) {
198
+ return this.handleStatelessAudio(text, options);
199
+ }
200
+ this.startAudioSession();
201
+ try {
202
+ await this.ttsPlayer.speak(text, options);
203
+ } finally {
204
+ this.endAudioSession();
205
+ }
206
+ }
207
+ /**
208
+ * Stateless 오디오 처리
209
+ */
210
+ async handleStatelessAudio(text, options) {
211
+ const audioData = await this.ttsPlayer.generateAudio(text, options);
212
+ const mimeType = getTTSAudioMimeType(this.ttsPlayer);
213
+ const blob = new Blob([audioData], { type: mimeType });
214
+ const audioUrl = URL.createObjectURL(blob);
215
+ return new Promise((resolve, reject) => {
216
+ const audio = new Audio(audioUrl);
217
+ this.currentAudio = audio;
218
+ this.currentAudioUrl = audioUrl;
219
+ if (options?.volume) {
220
+ audio.volume = Math.max(0, Math.min(1, options.volume));
221
+ }
222
+ this.startAudioSession(audio);
223
+ let isFinalized = false;
224
+ const finalize = (next) => {
225
+ if (isFinalized) return;
226
+ isFinalized = true;
227
+ if (this.currentAudioUrl) {
228
+ URL.revokeObjectURL(this.currentAudioUrl);
229
+ this.currentAudioUrl = null;
230
+ }
231
+ this.currentAudio = null;
232
+ this.endAudioSession();
233
+ next();
234
+ };
235
+ audio.onended = () => {
236
+ finalize(resolve);
237
+ };
238
+ audio.onerror = () => {
239
+ finalize(() => reject(new Error("Audio playback failed")));
240
+ };
241
+ audio.play().catch((error) => {
242
+ finalize(
243
+ () => reject(
244
+ error instanceof Error ? error : new Error("Audio playback failed")
245
+ )
246
+ );
247
+ });
248
+ });
249
+ }
250
+ startAudioSession(audioElement) {
251
+ if (this.isAudioSessionActive) {
252
+ return;
253
+ }
254
+ this.isAudioSessionActive = true;
255
+ this.eventEmitter?.emit("tts:audio:start", { audioElement });
256
+ }
257
+ endAudioSession() {
258
+ if (!this.isAudioSessionActive) {
259
+ return;
260
+ }
261
+ this.isAudioSessionActive = false;
262
+ this.eventEmitter?.emit("tts:audio:end", {});
263
+ }
264
+ };
265
+ function createTTSManager(ttsPlayer) {
266
+ return new TTSManagerImpl(ttsPlayer);
267
+ }
268
+ // Annotate the CommonJS export names for ESM import in node:
269
+ 0 && (module.exports = {
270
+ WebSpeechLipSyncSimulator,
271
+ createTTSManager,
272
+ getTTSAudioMimeType,
273
+ getTTSPlaybackMode,
274
+ supportsGenerateAudio
275
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,244 @@
1
+ // src/web-speech-lipsync-simulator.ts
2
+ var WebSpeechLipSyncSimulator = class {
3
+ intervals = [];
4
+ eventEmitter;
5
+ constructor(eventEmitter) {
6
+ this.eventEmitter = eventEmitter;
7
+ }
8
+ /**
9
+ * 텍스트 기반 립싱크 시뮬레이션 시작
10
+ */
11
+ startSimulation(text, rate = 1) {
12
+ this.clearIntervals();
13
+ if (!this.eventEmitter) return;
14
+ const words = text.split(/\s+/);
15
+ const baseInterval = 120 / rate;
16
+ let currentTime = 0;
17
+ words.forEach((word) => {
18
+ const intervalId = window.setTimeout(() => {
19
+ const vowels = (word.match(/[aeiouAEIOU]/g) || []).length;
20
+ const intensity = Math.min(0.3 + vowels * 0.15, 1);
21
+ this.eventEmitter?.emit("tts:lipsync:update", { rms: intensity });
22
+ this.createFadeEffect(intensity, baseInterval);
23
+ }, currentTime);
24
+ this.intervals.push(intervalId);
25
+ currentTime += baseInterval + word.length * 20 / rate;
26
+ });
27
+ }
28
+ /**
29
+ * 페이드 아웃 효과 생성
30
+ */
31
+ createFadeEffect(intensity, duration) {
32
+ const fadeSteps = 3;
33
+ for (let step = 1; step <= fadeSteps; step++) {
34
+ const fadeId = window.setTimeout(
35
+ () => {
36
+ const fadedIntensity = intensity * (1 - step / fadeSteps);
37
+ this.eventEmitter?.emit("tts:lipsync:update", {
38
+ rms: fadedIntensity
39
+ });
40
+ },
41
+ duration * step / fadeSteps
42
+ );
43
+ this.intervals.push(fadeId);
44
+ }
45
+ }
46
+ /**
47
+ * 시뮬레이션 중지
48
+ */
49
+ stopSimulation() {
50
+ this.clearIntervals();
51
+ if (this.eventEmitter) {
52
+ this.eventEmitter.emit("tts:lipsync:update", { rms: 0 });
53
+ }
54
+ }
55
+ /**
56
+ * 인터벌 정리
57
+ */
58
+ clearIntervals() {
59
+ this.intervals.forEach((id) => clearTimeout(id));
60
+ this.intervals = [];
61
+ }
62
+ /**
63
+ * 리소스 정리
64
+ */
65
+ dispose() {
66
+ this.stopSimulation();
67
+ }
68
+ };
69
+
70
+ // src/tts-utils.ts
71
+ function getTTSPlaybackMode(player) {
72
+ return player.playbackMode || "audio";
73
+ }
74
+ function getTTSAudioMimeType(player) {
75
+ return player.audioMimeType || "audio/wav";
76
+ }
77
+ function supportsGenerateAudio(player) {
78
+ return typeof player.generateAudio === "function";
79
+ }
80
+
81
+ // src/tts-manager.ts
82
+ var TTSManagerImpl = class {
83
+ ttsPlayer;
84
+ eventEmitter;
85
+ currentAudio = null;
86
+ currentAudioUrl = null;
87
+ playbackMode;
88
+ isAudioSessionActive = false;
89
+ // Web Speech 립싱크 시뮬레이션만 필요
90
+ webSimulator;
91
+ constructor(ttsPlayer) {
92
+ this.ttsPlayer = ttsPlayer;
93
+ this.playbackMode = getTTSPlaybackMode(ttsPlayer);
94
+ this.webSimulator = new WebSpeechLipSyncSimulator();
95
+ }
96
+ /**
97
+ * 이벤트 발신자 설정
98
+ */
99
+ setEventEmitter(eventEmitter) {
100
+ this.eventEmitter = eventEmitter;
101
+ this.webSimulator = new WebSpeechLipSyncSimulator(eventEmitter);
102
+ }
103
+ /**
104
+ * 텍스트 음성 변환 및 재생
105
+ */
106
+ async speak(text, options) {
107
+ await this.stop();
108
+ if (this.playbackMode === "web-speech") {
109
+ return this.handleWebSpeech(text, options);
110
+ } else {
111
+ return this.handleAudioSpeech(text, options);
112
+ }
113
+ }
114
+ /**
115
+ * 현재 재생 중인 음성 중지
116
+ */
117
+ async stop() {
118
+ this.webSimulator.stopSimulation();
119
+ try {
120
+ await this.ttsPlayer.stop();
121
+ } catch (error) {
122
+ console.warn("\u26A0\uFE0F TTS Manager: Failed to stop player cleanly", error);
123
+ }
124
+ if (this.currentAudio) {
125
+ this.currentAudio.onended = null;
126
+ this.currentAudio.onerror = null;
127
+ this.currentAudio.pause();
128
+ this.currentAudio = null;
129
+ }
130
+ if (this.currentAudioUrl) {
131
+ URL.revokeObjectURL(this.currentAudioUrl);
132
+ this.currentAudioUrl = null;
133
+ }
134
+ this.endAudioSession();
135
+ }
136
+ /**
137
+ * 음성 설정
138
+ */
139
+ setVoice(voice) {
140
+ this.ttsPlayer.setVoice(voice);
141
+ }
142
+ /**
143
+ * 지원 여부 확인
144
+ */
145
+ isSupported() {
146
+ return this.ttsPlayer.isSupported();
147
+ }
148
+ /**
149
+ * Web Speech API 처리 (시뮬레이션 립싱크)
150
+ */
151
+ async handleWebSpeech(text, options) {
152
+ const dummyAudio = document.createElement("audio");
153
+ dummyAudio.preload = "none";
154
+ this.startAudioSession(dummyAudio);
155
+ this.webSimulator.startSimulation(text, options?.rate || 1);
156
+ try {
157
+ await this.ttsPlayer.speak(text, options);
158
+ } finally {
159
+ this.webSimulator.stopSimulation();
160
+ this.endAudioSession();
161
+ }
162
+ }
163
+ /**
164
+ * Audio-based TTS 처리 (실시간 오디오 분석)
165
+ */
166
+ async handleAudioSpeech(text, options) {
167
+ if (supportsGenerateAudio(this.ttsPlayer)) {
168
+ return this.handleStatelessAudio(text, options);
169
+ }
170
+ this.startAudioSession();
171
+ try {
172
+ await this.ttsPlayer.speak(text, options);
173
+ } finally {
174
+ this.endAudioSession();
175
+ }
176
+ }
177
+ /**
178
+ * Stateless 오디오 처리
179
+ */
180
+ async handleStatelessAudio(text, options) {
181
+ const audioData = await this.ttsPlayer.generateAudio(text, options);
182
+ const mimeType = getTTSAudioMimeType(this.ttsPlayer);
183
+ const blob = new Blob([audioData], { type: mimeType });
184
+ const audioUrl = URL.createObjectURL(blob);
185
+ return new Promise((resolve, reject) => {
186
+ const audio = new Audio(audioUrl);
187
+ this.currentAudio = audio;
188
+ this.currentAudioUrl = audioUrl;
189
+ if (options?.volume) {
190
+ audio.volume = Math.max(0, Math.min(1, options.volume));
191
+ }
192
+ this.startAudioSession(audio);
193
+ let isFinalized = false;
194
+ const finalize = (next) => {
195
+ if (isFinalized) return;
196
+ isFinalized = true;
197
+ if (this.currentAudioUrl) {
198
+ URL.revokeObjectURL(this.currentAudioUrl);
199
+ this.currentAudioUrl = null;
200
+ }
201
+ this.currentAudio = null;
202
+ this.endAudioSession();
203
+ next();
204
+ };
205
+ audio.onended = () => {
206
+ finalize(resolve);
207
+ };
208
+ audio.onerror = () => {
209
+ finalize(() => reject(new Error("Audio playback failed")));
210
+ };
211
+ audio.play().catch((error) => {
212
+ finalize(
213
+ () => reject(
214
+ error instanceof Error ? error : new Error("Audio playback failed")
215
+ )
216
+ );
217
+ });
218
+ });
219
+ }
220
+ startAudioSession(audioElement) {
221
+ if (this.isAudioSessionActive) {
222
+ return;
223
+ }
224
+ this.isAudioSessionActive = true;
225
+ this.eventEmitter?.emit("tts:audio:start", { audioElement });
226
+ }
227
+ endAudioSession() {
228
+ if (!this.isAudioSessionActive) {
229
+ return;
230
+ }
231
+ this.isAudioSessionActive = false;
232
+ this.eventEmitter?.emit("tts:audio:end", {});
233
+ }
234
+ };
235
+ function createTTSManager(ttsPlayer) {
236
+ return new TTSManagerImpl(ttsPlayer);
237
+ }
238
+ export {
239
+ WebSpeechLipSyncSimulator,
240
+ createTTSManager,
241
+ getTTSAudioMimeType,
242
+ getTTSPlaybackMode,
243
+ supportsGenerateAudio
244
+ };