(
text: string,
textToSpeechConfig: ICommonObject,
options: ICommonObject,
abortController: AbortController,
onStart: (format: string) => void,
onChunk: (chunk: Buffer) => void,
onEnd: () => void
)
| 11 | } |
| 12 | |
| 13 | export const convertTextToSpeechStream = async ( |
| 14 | text: string, |
| 15 | textToSpeechConfig: ICommonObject, |
| 16 | options: ICommonObject, |
| 17 | abortController: AbortController, |
| 18 | onStart: (format: string) => void, |
| 19 | onChunk: (chunk: Buffer) => void, |
| 20 | onEnd: () => void |
| 21 | ): Promise<void> => { |
| 22 | return new Promise<void>((resolve, reject) => { |
| 23 | let streamDestroyed = false |
| 24 | |
| 25 | // Handle abort signal early |
| 26 | if (abortController.signal.aborted) { |
| 27 | reject(new Error('TTS generation aborted')) |
| 28 | return |
| 29 | } |
| 30 | const processStream = async () => { |
| 31 | try { |
| 32 | if (textToSpeechConfig) { |
| 33 | const credentialId = textToSpeechConfig.credentialId as string |
| 34 | const credentialData = await getCredentialData(credentialId ?? '', options) |
| 35 | |
| 36 | switch (textToSpeechConfig.name) { |
| 37 | case TextToSpeechType.OPENAI_TTS: { |
| 38 | onStart('mp3') |
| 39 | |
| 40 | const openai = new OpenAI({ |
| 41 | apiKey: credentialData.openAIApiKey |
| 42 | }) |
| 43 | |
| 44 | const response = await openai.audio.speech.create( |
| 45 | { |
| 46 | model: 'gpt-4o-mini-tts', |
| 47 | voice: (textToSpeechConfig.voice || 'alloy') as |
| 48 | | 'alloy' |
| 49 | | 'ash' |
| 50 | | 'ballad' |
| 51 | | 'coral' |
| 52 | | 'echo' |
| 53 | | 'fable' |
| 54 | | 'nova' |
| 55 | | 'onyx' |
| 56 | | 'sage' |
| 57 | | 'shimmer', |
| 58 | input: text, |
| 59 | response_format: 'mp3' |
| 60 | }, |
| 61 | { |
| 62 | signal: abortController.signal |
| 63 | } |
| 64 | ) |
| 65 | |
| 66 | const stream = Readable.fromWeb(response.body as unknown as ReadableStream) |
| 67 | if (!stream) { |
| 68 | throw new Error('Failed to get response stream') |
| 69 | } |
| 70 |
no test coverage detected