import { Injectable, HttpException, HttpStatus } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; @Injectable() export class VoiceService { private readonly voiceServiceUrl: string; constructor(private configService: ConfigService) { const voiceServiceHost = this.configService.get('VOICE_SERVICE_HOST'); if (!voiceServiceHost) { throw new Error('VOICE_SERVICE_HOST environment variable is not set'); } this.voiceServiceUrl = voiceServiceHost; } async generateTTS(text: string, voice: string = 'sarah'): Promise { try { const url = `${this.voiceServiceUrl}/api/voice/tts`; const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text, voice }), }); if (!response.ok) { throw new HttpException( `Voice service error: ${response.statusText}`, response.status || HttpStatus.INTERNAL_SERVER_ERROR, ); } const arrayBuffer = await response.arrayBuffer(); return Buffer.from(arrayBuffer); } catch (error) { if (error instanceof HttpException) { throw error; } throw new HttpException( `Failed to generate speech: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR, ); } } async getEffect(effectType: string): Promise { try { const url = `${this.voiceServiceUrl}/api/voice/effects/${effectType}`; const response = await fetch(url, { method: 'GET', }); if (!response.ok) { throw new HttpException( `Voice service error: ${response.statusText}`, response.status || HttpStatus.INTERNAL_SERVER_ERROR, ); } const arrayBuffer = await response.arrayBuffer(); return Buffer.from(arrayBuffer); } catch (error) { if (error instanceof HttpException) { throw error; } throw new HttpException( `Failed to get sound effect: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR, ); } } }