@@ -108,5 +108,96 @@ export function useTextToVoice() {
108108 }
109109 } ;
110110
111- return { convertTextToBase64Audio, decodeAndPlayAudio, textToVoice} ;
111+ const textToVoice3 = async ( text : string ) => {
112+ try {
113+ const response = await fetch ( 'http://localhost:3001/tts' , {
114+ method : 'POST' ,
115+ headers : {
116+ 'Content-Type' : 'application/json' ,
117+ } ,
118+ body : JSON . stringify ( { text} ) ,
119+ } ) ;
120+
121+ if ( ! response . ok ) {
122+ throw new Error ( 'Failed to fetch TTS audio' ) ;
123+ }
124+
125+ const blob = await response . blob ( ) ;
126+ const audioURL = URL . createObjectURL ( blob ) ;
127+
128+ const audio = new Audio ( audioURL ) ;
129+ audio . play ( ) ;
130+
131+ return Promise . resolve ( audioURL ) ;
132+ } catch ( error ) {
133+ console . error ( 'Error on useTextToVoice - textToVoice (via proxy)' , error ) ;
134+ return Promise . reject ( error ) ;
135+ }
136+ } ;
137+
138+ const textToVoice2 = async ( text : string ) => {
139+ try {
140+ const response = await fetch ( 'http://localhost:3001/tts' , {
141+ method : 'POST' ,
142+ headers : { 'Content-Type' : 'application/json' } ,
143+ body : JSON . stringify ( { text} ) ,
144+ } ) ;
145+
146+ if ( ! response . ok ) throw new Error ( 'TTS streaming failed' ) ;
147+
148+ const mediaSource = new MediaSource ( ) ;
149+ const audio = new Audio ( ) ;
150+ audio . src = URL . createObjectURL ( mediaSource ) ;
151+ audio . play ( ) . then ( ( ) => {
152+ console . log ( '[TTS] Audio playback started' ) ;
153+ } ) ;
154+
155+ mediaSource . addEventListener ( 'sourceopen' , ( ) => {
156+ console . log ( '[TTS] MediaSource opened' ) ;
157+ const sourceBuffer = mediaSource . addSourceBuffer ( 'audio/mpeg' ) ;
158+
159+ const reader = response . body ?. getReader ( ) ;
160+ const pump = ( ) => {
161+ if ( ! reader ) return ;
162+ reader . read ( ) . then ( ( { done, value} ) => {
163+ if ( done ) {
164+ console . log ( '[TTS] All chunks received. Closing stream...' ) ;
165+ if ( ! sourceBuffer . updating ) mediaSource . endOfStream ( ) ;
166+ return ;
167+ }
168+ if ( ! value ) return ;
169+
170+ console . log (
171+ `[TTS] 🔄 Received audio chunk: ${ value . byteLength } bytes` ,
172+ ) ;
173+
174+ if ( ! sourceBuffer . updating ) {
175+ sourceBuffer . appendBuffer ( value ) ;
176+ pump ( ) ;
177+ } else {
178+ sourceBuffer . addEventListener (
179+ 'updateend' ,
180+ ( ) => {
181+ sourceBuffer . appendBuffer ( value ) ;
182+ pump ( ) ;
183+ } ,
184+ { once : true } ,
185+ ) ;
186+ }
187+ } ) ;
188+ } ;
189+
190+ pump ( ) ;
191+ } ) ;
192+ } catch ( error ) {
193+ console . error ( '[TTS] Error in streaming text-to-voice:' , error ) ;
194+ }
195+ } ;
196+
197+ return {
198+ convertTextToBase64Audio,
199+ decodeAndPlayAudio,
200+ textToVoice,
201+ textToVoice2,
202+ } ;
112203}
0 commit comments