1
- import { getLatestVoice } from "@/lib/db/queries"
2
- import { auth } from "@/app/(auth)/auth"
3
- import { NextResponse } from "next/server"
1
+ import { getLatestVoice } from "@/lib/db/queries" ;
2
+ import { auth } from "@/app/(auth)/auth" ;
3
+ import { NextResponse } from "next/server" ;
4
+ const https = require ( "https" ) ;
4
5
5
6
export async function POST ( request : Request ) {
6
7
try {
7
- const { text, voice } = await request . json ( )
8
+ const { text, voice } = await request . json ( ) ;
8
9
const session = await auth ( ) ;
9
10
const user_id = session ?. user ?. id ?? "" ;
10
- const latestVoice = await getLatestVoice ( user_id )
11
+ const latestVoice = await getLatestVoice ( user_id ) ;
11
12
12
- const response = await fetch ( `https://api.elevenlabs.io/v1/text-to-speech/${ latestVoice ?. voice_id ?? voice } ` , {
13
+ const options = {
14
+ hostname : "api.elevenlabs.io" ,
15
+ path : `/v1/text-to-speech/${ latestVoice ?. voice_id ?? voice } /stream` ,
13
16
method : "POST" ,
14
17
headers : {
15
18
"Content-Type" : "application/json" ,
16
19
"xi-api-key" : process . env . ELEVENLABS_API_KEY ! ,
17
20
} ,
18
- body : JSON . stringify ( {
19
- text,
20
- model_id : "eleven_monolingual_v1" ,
21
- voice_settings : {
22
- stability : 0.5 ,
23
- similarity_boost : 0.5 ,
24
- } ,
25
- } ) ,
26
- } )
21
+ } ;
27
22
28
- console . log ( "TTS response" , response )
23
+ const requestBody = JSON . stringify ( {
24
+ text,
25
+ model_id : "eleven_monolingual_v1" ,
26
+ voice_settings : {
27
+ stability : 0.5 ,
28
+ similarity_boost : 0.5 ,
29
+ } ,
30
+ } ) ;
31
+
32
+ const stream = new ReadableStream ( {
33
+ async start ( controller ) {
34
+ const req = https . request ( options , ( res : any ) => {
35
+ if ( res . statusCode !== 200 ) {
36
+ controller . error ( new Error ( "Failed to generate speech" ) ) ;
37
+ return ;
38
+ }
39
+
40
+ res . on ( "data" , ( chunk : any ) => {
41
+ controller . enqueue ( chunk ) ;
42
+ } ) ;
29
43
30
- if ( ! response . ok ) {
31
- throw new Error ( "Failed to generate speech" )
32
- }
44
+ res . on ( "end" , ( ) => {
45
+ controller . close ( ) ;
46
+ } ) ;
47
+ } ) ;
33
48
34
- const audioBuffer = await response . arrayBuffer ( )
49
+ req . on ( "error" , ( e : any ) => {
50
+ controller . error ( e ) ;
51
+ } ) ;
52
+
53
+ req . write ( requestBody ) ;
54
+ req . end ( ) ;
55
+ } ,
56
+ } ) ;
35
57
36
- return new NextResponse ( audioBuffer , {
58
+ return new NextResponse ( stream , {
37
59
headers : {
38
60
"Content-Type" : "audio/mpeg" ,
39
61
} ,
40
- } )
62
+ } ) ;
41
63
} catch ( error ) {
42
- console . error ( "Error:" , error )
43
- return NextResponse . json ( { error : "Failed to generate speech" } , { status : 500 } )
64
+ console . error ( "Error:" , error ) ;
65
+ return NextResponse . json (
66
+ { error : "Failed to generate speech" } ,
67
+ { status : 500 }
68
+ ) ;
44
69
}
45
- }
70
+ }
0 commit comments