forked from THU-MAIC/OpenMAIC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtts-providers.ts
More file actions
412 lines (368 loc) · 12.3 KB
/
tts-providers.ts
File metadata and controls
412 lines (368 loc) · 12.3 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/**
* TTS (Text-to-Speech) Provider Implementation
*
* Factory pattern for routing TTS requests to appropriate provider implementations.
* Follows the same architecture as lib/ai/providers.ts for consistency.
*
* Currently Supported Providers:
* - OpenAI TTS: https://platform.openai.com/docs/guides/text-to-speech
* - Azure TTS: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/text-to-speech
* - GLM TTS: https://docs.bigmodel.cn/cn/guide/models/sound-and-video/glm-tts
* - Qwen TTS: https://bailian.console.aliyun.com/
* - ElevenLabs TTS: https://elevenlabs.io/docs/api-reference/text-to-speech/convert
* - Browser Native: Web Speech API (client-side only)
*
* HOW TO ADD A NEW PROVIDER:
*
* 1. Add provider ID to TTSProviderId in lib/audio/types.ts
* Example: | 'elevenlabs-tts'
*
* 2. Add provider configuration to lib/audio/constants.ts
* Example:
* 'elevenlabs-tts': {
* id: 'elevenlabs-tts',
* name: 'ElevenLabs',
* requiresApiKey: true,
* defaultBaseUrl: 'https://api.elevenlabs.io/v1',
* icon: '/logos/elevenlabs.svg',
* voices: [...],
* supportedFormats: ['mp3', 'pcm'],
* speedRange: { min: 0.5, max: 2.0, default: 1.0 }
* }
*
* 3. Implement provider function in this file
* Pattern: async function generateXxxTTS(config, text): Promise<TTSGenerationResult>
* - Validate config and build API request
* - Handle API authentication (apiKey, headers)
* - Convert provider-specific parameters (voice, speed, format)
* - Return { audio: Uint8Array, format: string }
*
* Example:
* async function generateElevenLabsTTS(
* config: TTSModelConfig,
* text: string
* ): Promise<TTSGenerationResult> {
* const baseUrl = config.baseUrl || TTS_PROVIDERS['elevenlabs-tts'].defaultBaseUrl;
*
* const response = await fetch(`${baseUrl}/text-to-speech/${config.voice}`, {
* method: 'POST',
* headers: {
* 'xi-api-key': config.apiKey!,
* 'Content-Type': 'application/json',
* },
* body: JSON.stringify({
* text,
* model_id: 'eleven_multilingual_v2',
* voice_settings: {
* stability: 0.5,
* similarity_boost: 0.75,
* }
* }),
* });
*
* if (!response.ok) {
* throw new Error(`ElevenLabs TTS API error: ${response.statusText}`);
* }
*
* const arrayBuffer = await response.arrayBuffer();
* return {
* audio: new Uint8Array(arrayBuffer),
* format: 'mp3',
* };
* }
*
* 4. Add case to generateTTS() switch statement
* case 'elevenlabs-tts':
* return await generateElevenLabsTTS(config, text);
*
* 5. Add i18n translations in lib/i18n.ts
* providerElevenLabsTTS: { zh: 'ElevenLabs TTS', en: 'ElevenLabs TTS' }
*
* Error Handling Patterns:
* - Always validate API key if requiresApiKey is true
* - Throw descriptive errors for API failures
* - Include response.statusText or error messages from API
* - For client-only providers (browser-native), throw error directing to client-side usage
*
* API Call Patterns:
* - Direct API: Use fetch with appropriate headers and body format (recommended for better encoding support)
* - SSML: For Azure-like providers requiring SSML markup
* - URL-based: For providers returning audio URL (download in second step)
*/
import type { TTSModelConfig } from './types';
import { TTS_PROVIDERS } from './constants';
/**
* Result of TTS generation
*/
export interface TTSGenerationResult {
audio: Uint8Array;
format: string;
}
/**
* Generate speech using specified TTS provider
*/
export async function generateTTS(
config: TTSModelConfig,
text: string,
): Promise<TTSGenerationResult> {
const provider = TTS_PROVIDERS[config.providerId];
if (!provider) {
throw new Error(`Unknown TTS provider: ${config.providerId}`);
}
// Validate API key if required
if (provider.requiresApiKey && !config.apiKey) {
throw new Error(`API key required for TTS provider: ${config.providerId}`);
}
switch (config.providerId) {
case 'openai-tts':
return await generateOpenAITTS(config, text);
case 'azure-tts':
return await generateAzureTTS(config, text);
case 'glm-tts':
return await generateGLMTTS(config, text);
case 'qwen-tts':
return await generateQwenTTS(config, text);
case 'elevenlabs-tts':
return await generateElevenLabsTTS(config, text);
case 'browser-native-tts':
throw new Error(
'Browser Native TTS must be handled client-side using Web Speech API. This provider cannot be used on the server.',
);
default:
throw new Error(`Unsupported TTS provider: ${config.providerId}`);
}
}
/**
* OpenAI TTS implementation (direct API call with explicit UTF-8 encoding)
*/
async function generateOpenAITTS(
config: TTSModelConfig,
text: string,
): Promise<TTSGenerationResult> {
const baseUrl = config.baseUrl || TTS_PROVIDERS['openai-tts'].defaultBaseUrl;
// Use gpt-4o-mini-tts for best quality and intelligent realtime applications
const response = await fetch(`${baseUrl}/audio/speech`, {
method: 'POST',
headers: {
Authorization: `Bearer ${config.apiKey}`,
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify({
model: 'gpt-4o-mini-tts',
input: text,
voice: config.voice,
speed: config.speed || 1.0,
}),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ error: response.statusText }));
throw new Error(`OpenAI TTS API error: ${error.error?.message || response.statusText}`);
}
const arrayBuffer = await response.arrayBuffer();
return {
audio: new Uint8Array(arrayBuffer),
format: 'mp3',
};
}
/**
* Azure TTS implementation (direct API call with SSML)
*/
async function generateAzureTTS(
config: TTSModelConfig,
text: string,
): Promise<TTSGenerationResult> {
const baseUrl = config.baseUrl || TTS_PROVIDERS['azure-tts'].defaultBaseUrl;
// Build SSML
const rate = config.speed ? `${((config.speed - 1) * 100).toFixed(0)}%` : '0%';
const ssml = `
<speak version='1.0' xml:lang='zh-CN'>
<voice xml:lang='zh-CN' name='${config.voice}'>
<prosody rate='${rate}'>${escapeXml(text)}</prosody>
</voice>
</speak>
`.trim();
const response = await fetch(`${baseUrl}/cognitiveservices/v1`, {
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': config.apiKey!,
'Content-Type': 'application/ssml+xml; charset=utf-8',
'X-Microsoft-OutputFormat': 'audio-16khz-128kbitrate-mono-mp3',
},
body: ssml,
});
if (!response.ok) {
throw new Error(`Azure TTS API error: ${response.statusText}`);
}
const arrayBuffer = await response.arrayBuffer();
return {
audio: new Uint8Array(arrayBuffer),
format: 'mp3',
};
}
/**
* GLM TTS implementation (GLM API)
*/
async function generateGLMTTS(config: TTSModelConfig, text: string): Promise<TTSGenerationResult> {
const baseUrl = config.baseUrl || TTS_PROVIDERS['glm-tts'].defaultBaseUrl;
const response = await fetch(`${baseUrl}/audio/speech`, {
method: 'POST',
headers: {
Authorization: `Bearer ${config.apiKey}`,
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify({
model: 'glm-tts',
input: text,
voice: config.voice,
speed: config.speed || 1.0,
volume: 1.0,
response_format: 'wav',
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => response.statusText);
let errorMessage = `GLM TTS API error: ${errorText}`;
try {
const errorJson = JSON.parse(errorText);
if (errorJson.error?.message) {
errorMessage = `GLM TTS API error: ${errorJson.error.message} (code: ${errorJson.error.code})`;
}
} catch {
// If not JSON, use the text as is
}
throw new Error(errorMessage);
}
const arrayBuffer = await response.arrayBuffer();
return {
audio: new Uint8Array(arrayBuffer),
format: 'wav',
};
}
/**
* Qwen TTS implementation (DashScope API - Qwen3 TTS Flash)
*/
async function generateQwenTTS(config: TTSModelConfig, text: string): Promise<TTSGenerationResult> {
const baseUrl = config.baseUrl || TTS_PROVIDERS['qwen-tts'].defaultBaseUrl;
// Calculate speed: Qwen3 uses rate parameter from -500 to 500
// speed 1.0 = rate 0, speed 2.0 = rate 500, speed 0.5 = rate -250
const rate = Math.round(((config.speed || 1.0) - 1.0) * 500);
const response = await fetch(`${baseUrl}/services/aigc/multimodal-generation/generation`, {
method: 'POST',
headers: {
Authorization: `Bearer ${config.apiKey}`,
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify({
model: 'qwen3-tts-flash',
input: {
text,
voice: config.voice,
language_type: 'Chinese', // Default to Chinese, can be made configurable
},
parameters: {
rate, // Speech rate from -500 to 500
},
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => response.statusText);
throw new Error(`Qwen TTS API error: ${errorText}`);
}
const data = await response.json();
// Check for audio URL in response
if (!data.output?.audio?.url) {
throw new Error(`Qwen TTS error: No audio URL in response. Response: ${JSON.stringify(data)}`);
}
// Download audio from URL
const audioUrl = data.output.audio.url;
const audioResponse = await fetch(audioUrl);
if (!audioResponse.ok) {
throw new Error(`Failed to download audio from URL: ${audioResponse.statusText}`);
}
const arrayBuffer = await audioResponse.arrayBuffer();
return {
audio: new Uint8Array(arrayBuffer),
format: 'wav', // Qwen3 TTS returns WAV format
};
}
/**
* ElevenLabs TTS implementation (direct API call with voice-specific endpoint)
*/
async function generateElevenLabsTTS(
config: TTSModelConfig,
text: string,
): Promise<TTSGenerationResult> {
const baseUrl = config.baseUrl || TTS_PROVIDERS['elevenlabs-tts'].defaultBaseUrl;
const requestedFormat = config.format || 'mp3';
const clampedSpeed = Math.min(1.2, Math.max(0.7, config.speed || 1.0));
const outputFormatMap: Record<string, string> = {
mp3: 'mp3_44100_128',
opus: 'opus_48000_96',
pcm: 'pcm_44100',
wav: 'wav_44100',
ulaw: 'ulaw_8000',
alaw: 'alaw_8000',
};
const outputFormat = outputFormatMap[requestedFormat] || outputFormatMap.mp3;
const response = await fetch(
`${baseUrl}/text-to-speech/${encodeURIComponent(config.voice)}?output_format=${outputFormat}`,
{
method: 'POST',
headers: {
'xi-api-key': config.apiKey!,
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify({
text,
model_id: 'eleven_multilingual_v2',
voice_settings: {
stability: 0.5,
similarity_boost: 0.75,
speed: clampedSpeed,
},
}),
},
);
if (!response.ok) {
const errorText = await response.text().catch(() => response.statusText);
throw new Error(`ElevenLabs TTS API error: ${errorText || response.statusText}`);
}
const arrayBuffer = await response.arrayBuffer();
return {
audio: new Uint8Array(arrayBuffer),
format: requestedFormat,
};
}
/**
* Get current TTS configuration from settings store
* Note: This function should only be called in browser context
*/
export async function getCurrentTTSConfig(): Promise<TTSModelConfig> {
if (typeof window === 'undefined') {
throw new Error('getCurrentTTSConfig() can only be called in browser context');
}
// Lazy import to avoid circular dependency
const { useSettingsStore } = await import('@/lib/store/settings');
const { ttsProviderId, ttsVoice, ttsSpeed, ttsProvidersConfig } = useSettingsStore.getState();
const providerConfig = ttsProvidersConfig?.[ttsProviderId];
return {
providerId: ttsProviderId,
apiKey: providerConfig?.apiKey,
baseUrl: providerConfig?.baseUrl,
voice: ttsVoice,
speed: ttsSpeed,
};
}
// Re-export from constants for convenience
export { getAllTTSProviders, getTTSProvider, getTTSVoices } from './constants';
/**
* Escape XML special characters for SSML
*/
function escapeXml(text: string): string {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}