Open History to see the last commit
1import { useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { Download, Loader2, Volume2 } from 'lucide-react'
4
5type Voice =
6 | 'alloy'
7 | 'ash'
8 | 'ballad'
9 | 'coral'
10 | 'echo'
11 | 'fable'
12 | 'onyx'
13 | 'nova'
14 | 'sage'
15 | 'shimmer'
16 | 'verse'
17type Model = 'tts-1' | 'tts-1-hd' | 'gpt-4o-audio-preview'
18type Format = 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'
19
20interface TTSResult {
21 id: string
22 model: string
23 audio: string
24 format: string
25 contentType?: string
26 duration?: number
27}
28
29const VOICES: Array<{ value: Voice; label: string }> = [
30 { value: 'alloy', label: 'Alloy' },
31 { value: 'ash', label: 'Ash' },
32 { value: 'ballad', label: 'Ballad' },
33 { value: 'coral', label: 'Coral' },
34 { value: 'echo', label: 'Echo' },
35 { value: 'fable', label: 'Fable' },
36 { value: 'onyx', label: 'Onyx' },
37 { value: 'nova', label: 'Nova' },
38 { value: 'sage', label: 'Sage' },
39 { value: 'shimmer', label: 'Shimmer' },
40 { value: 'verse', label: 'Verse' },
41]
42
43const MODELS: Array<{ value: Model; label: string }> = [
44 { value: 'tts-1', label: 'TTS-1 (Fast)' },
45 { value: 'tts-1-hd', label: 'TTS-1-HD (High Quality)' },
46 { value: 'gpt-4o-audio-preview', label: 'GPT-4o Audio (Preview)' },
47]
48
49const FORMATS: Array<{ value: Format; label: string }> = [
50 { value: 'mp3', label: 'MP3' },
51 { value: 'opus', label: 'Opus' },
52 { value: 'aac', label: 'AAC' },
53 { value: 'flac', label: 'FLAC' },
54 { value: 'wav', label: 'WAV' },
55 { value: 'pcm', label: 'PCM' },
56]
57
58function TTSPage() {
59 const [text, setText] = useState(
60 'Hello! Welcome to TanStack AI. This is a demonstration of text-to-speech synthesis.',
61 )
62 const [voice, setVoice] = useState<Voice>('nova')
63 const [model, setModel] = useState<Model>('tts-1')
64 const [format, setFormat] = useState<Format>('mp3')
65 const [speed, setSpeed] = useState(1.0)
66 const [result, setResult] = useState<TTSResult | null>(null)
67 const [isLoading, setIsLoading] = useState(false)
68 const [error, setError] = useState<string | null>(null)
69 const audioRef = useRef<HTMLAudioElement>(null)
70
71 const handleGenerate = async () => {
72 setIsLoading(true)
73 setError(null)
74 setResult(null)
75
76 try {
77 const response = await fetch('/api/tts', {
78 method: 'POST',
79 headers: { 'Content-Type': 'application/json' },
80 body: JSON.stringify({
81 text,
82 voice,
83 model,
84 format,
85 speed,
86 }),
87 })
88
89 const data = await response.json()
90
91 if (!response.ok) {
92 throw new Error(data.error || 'Failed to generate speech')
93 }
94
95 setResult(data)
96 } catch (err: any) {
97 setError(err.message)
98 } finally {
99 setIsLoading(false)
100 }
101 }
102
103 const handleDownload = () => {
104 if (!result) return
105
106 const mimeType = result.contentType || `audio/${result.format}`
107 const byteCharacters = atob(result.audio)
108 const byteNumbers = new Array(byteCharacters.length)
109 for (let i = 0; i < byteCharacters.length; i++) {
110 byteNumbers[i] = byteCharacters.charCodeAt(i)
111 }
112 const byteArray = new Uint8Array(byteNumbers)
113 const blob = new Blob([byteArray], { type: mimeType })
114
115 const url = URL.createObjectURL(blob)
116 const a = document.createElement('a')
117 a.href = url
118 a.download = `speech-${result.id}.${result.format}`
119 document.body.appendChild(a)
120 a.click()
121 document.body.removeChild(a)
122 URL.revokeObjectURL(url)
123 }
124
125 const audioSrc = result
126 ? `data:${result.contentType || `audio/${result.format}`};base64,${result.audio}`
127 : undefined
128
129 return (
130 <div className="min-h-[calc(100vh-72px)] bg-gray-900 p-6">
131 <div className="max-w-4xl mx-auto">
132 {/* Header */}
133 <div className="flex items-center gap-3 mb-6">
134 <Volume2 className="w-8 h-8 text-emerald-500" />
135 <h1 className="text-2xl font-bold text-white">Text-to-Speech</h1>
136 </div>
137
138 <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
139 {/* Input Panel */}
140 <div className="space-y-4">
141 <div>
142 <label className="block text-sm font-medium text-gray-300 mb-2">
143 Text
144 </label>
145 <textarea
146 value={text}
147 onChange={(e) => setText(e.target.value)}
148 disabled={isLoading}
149 rows={6}
150 maxLength={4096}
151 className="w-full rounded-lg border border-emerald-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 resize-none"
152 placeholder="Enter text to convert to speech..."
153 />
154 <p className="mt-1 text-xs text-gray-500">
155 {text.length} / 4096 characters
156 </p>
157 </div>
158
159 <div className="grid grid-cols-2 gap-4">
160 <div>
161 <label className="block text-sm font-medium text-gray-300 mb-2">
162 Voice
163 </label>
164 <select
165 value={voice}
166 onChange={(e) => setVoice(e.target.value as Voice)}
167 disabled={isLoading}
168 className="w-full rounded-lg border border-emerald-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
169 >
170 {VOICES.map((v) => (
171 <option key={v.value} value={v.value}>
172 {v.label}
173 </option>
174 ))}
175 </select>
176 </div>
177 <div>
178 <label className="block text-sm font-medium text-gray-300 mb-2">
179 Model
180 </label>
181 <select
182 value={model}
183 onChange={(e) => setModel(e.target.value as Model)}
184 disabled={isLoading}
185 className="w-full rounded-lg border border-emerald-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
186 >
187 {MODELS.map((m) => (
188 <option key={m.value} value={m.value}>
189 {m.label}
190 </option>
191 ))}
192 </select>
193 </div>
194 </div>
195
196 <div className="grid grid-cols-2 gap-4">
197 <div>
198 <label className="block text-sm font-medium text-gray-300 mb-2">
199 Format
200 </label>
201 <select
202 value={format}
203 onChange={(e) => setFormat(e.target.value as Format)}
204 disabled={isLoading}
205 className="w-full rounded-lg border border-emerald-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
206 >
207 {FORMATS.map((f) => (
208 <option key={f.value} value={f.value}>
209 {f.label}
210 </option>
211 ))}
212 </select>
213 </div>
214 <div>
215 <label className="block text-sm font-medium text-gray-300 mb-2">
216 Speed ({speed.toFixed(2)}x)
217 </label>
218 <input
219 type="range"
220 min="0.25"
221 max="4.0"
222 step="0.05"
223 value={speed}
224 onChange={(e) => setSpeed(parseFloat(e.target.value))}
225 disabled={isLoading}
226 className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-emerald-500"
227 />
228 </div>
229 </div>
230
231 <button
232 onClick={handleGenerate}
233 disabled={isLoading || !text.trim()}
234 className="w-full px-4 py-3 bg-emerald-600 hover:bg-emerald-700 disabled:bg-gray-600 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
235 >
236 {isLoading ? (
237 <>
238 <Loader2 className="w-5 h-5 animate-spin" />
239 Generating...
240 </>
241 ) : (
242 <>
243 <Volume2 className="w-5 h-5" />
244 Generate Speech
245 </>
246 )}
247 </button>
248 </div>
249
250 {/* Output Panel */}
251 <div className="bg-gray-800 rounded-lg p-6 border border-emerald-500/20">
252 <h2 className="text-lg font-semibold text-white mb-4">
253 Generated Audio
254 </h2>
255
256 {error && (
257 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 mb-4">
258 {error}
259 </div>
260 )}
261
262 {result ? (
263 <div className="space-y-4">
264 <div className="relative group">
265 <audio
266 ref={audioRef}
267 src={audioSrc}
268 controls
269 className="w-full rounded-lg"
270 />
271 <button
272 onClick={handleDownload}
273 className="absolute top-2 right-2 p-2 bg-gray-900/80 hover:bg-gray-900 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity"
274 title="Download audio"
275 >
276 <Download className="w-4 h-4 text-white" />
277 </button>
278 </div>
279 <div className="pt-4 border-t border-gray-700 text-sm text-gray-400">
280 <p>
281 Model:{' '}
282 <span className="text-emerald-400">{result.model}</span>
283 </p>
284 <p>
285 Voice: <span className="text-emerald-400">{voice}</span>
286 </p>
287 <p>
288 Format:{' '}
289 <span className="text-emerald-400">{result.format}</span>
290 </p>
291 {result.duration && (
292 <p>
293 Duration:{' '}
294 <span className="text-emerald-400">
295 {result.duration}s
296 </span>
297 </p>
298 )}
299 </div>
300 </div>
301 ) : !error && !isLoading ? (
302 <div className="flex flex-col items-center justify-center h-48 text-gray-500">
303 <Volume2 className="w-16 h-16 mb-4 opacity-50" />
304 <p>Enter text and click "Generate Speech" to create audio.</p>
305 </div>
306 ) : null}
307 </div>
308 </div>
309 </div>
310 </div>
311 )
312}
313
314export const Route = createFileRoute('/tts')({
315 component: TTSPage,
316})