75 lines
2.1 KiB
TypeScript
75 lines
2.1 KiB
TypeScript
|
|
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||
|
|
import { ConfigService } from '@nestjs/config';
|
||
|
|
|
||
|
|
@Injectable()
|
||
|
|
export class VoiceService {
|
||
|
|
private readonly voiceServiceUrl: string;
|
||
|
|
|
||
|
|
constructor(private configService: ConfigService) {
|
||
|
|
this.voiceServiceUrl = this.configService.get<string>('VOICE_SERVICE_HOST');
|
||
|
|
|
||
|
|
if (!this.voiceServiceUrl) {
|
||
|
|
throw new Error('VOICE_SERVICE_HOST environment variable is not set');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
async generateTTS(text: string, voice: string = 'sarah'): Promise<Buffer> {
|
||
|
|
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<Buffer> {
|
||
|
|
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,
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|