Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.tts.ts

69 lines1.7 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { generateSpeech } from '@tanstack/ai'
3import { openaiSpeech } from '@tanstack/ai-openai'
4​
5export const Route = createFileRoute('/api/tts')({
6 server: {
7 handlers: {
8 POST: async ({ request }) => {
9 const body = await request.json()
10 const {
11 text,
12 voice = 'alloy',
13 model = 'tts-1',
14 format = 'mp3',
15 speed = 1.0,
16 } = body
17​
18 if (!text || text.trim().length === 0) {
19 return new Response(
20 JSON.stringify({
21 error: 'Text is required',
22 }),
23 {
24 status: 400,
25 headers: { 'Content-Type': 'application/json' },
26 },
27 )
28 }
29​
30 try {
31 const adapter = openaiSpeech(model)
32​
33 const result = await generateSpeech({
34 adapter,
35 text,
36 voice,
37 format,
38 speed,
39 })
40​
41 return new Response(
42 JSON.stringify({
43 id: result.id,
44 model: result.model,
45 audio: result.audio,
46 format: result.format,
47 contentType: result.contentType,
48 duration: result.duration,
49 }),
50 {
51 status: 200,
52 headers: { 'Content-Type': 'application/json' },
53 },
54 )
55 } catch (error: any) {
56 return new Response(
57 JSON.stringify({
58 error: error.message || 'An error occurred',
59 }),
60 {
61 status: 500,
62 headers: { 'Content-Type': 'application/json' },
63 },
64 )
65 }
66 },
67 },
68 },
69})