@@ -997,16 +997,52 @@ <h1>Yuhasa History Tutor</h1>
997997 alert ( 'Attachment functionality is not yet implemented.' ) ;
998998 } ) ;
999999
1000- speakerButton . addEventListener ( 'click' , ( ) => {
1001- alert ( 'Text-to-speech functionality is not yet implemented.' ) ;
1002- } ) ;
1000+ // speakerButton.addEventListener('click', () => {
1001+ // alert('Text-to-speech functionality is not yet implemented.');
1002+ // });
10031003
10041004 // --- Initial Setup ---
10051005 loadChatHistoryList ( true ) ; // Load the list of chats and select latest on page load
10061006 userInput . focus ( ) ;
10071007 autoResizeTextarea ( ) ;
10081008 } ) ;
10091009 </ script >
1010+
1011+ < script >
1012+ document . getElementById ( 'speakerButton' ) . addEventListener ( 'click' , async function ( ) {
1013+ // Find all bot messages in the chat
1014+ const botMessages = Array . from ( document . querySelectorAll ( '.bot-message .message-bubble' ) ) ;
1015+ if ( botMessages . length === 0 ) {
1016+ alert ( 'No bot message to speak!' ) ;
1017+ return ;
1018+ }
1019+ // Get the last bot message's text
1020+ const lastBotMsg = botMessages [ botMessages . length - 1 ] . innerText . trim ( ) ;
1021+ if ( ! lastBotMsg ) {
1022+ alert ( 'Bot message is empty!' ) ;
1023+ return ;
1024+ }
1025+ try {
1026+ // Send the text to the /tts endpoint
1027+ const response = await fetch ( '/tts' , {
1028+ method : 'POST' ,
1029+ headers : { 'Content-Type' : 'application/json' } ,
1030+ body : JSON . stringify ( { text : lastBotMsg } )
1031+ } ) ;
1032+ if ( ! response . ok ) {
1033+ throw new Error ( 'TTS failed' ) ;
1034+ }
1035+ const blob = await response . blob ( ) ;
1036+ // Play the audio using an Audio element
1037+ const audioUrl = URL . createObjectURL ( blob ) ;
1038+ const audio = new Audio ( audioUrl ) ;
1039+ audio . play ( ) ;
1040+ } catch ( err ) {
1041+ alert ( 'Failed to speak: ' + err . message ) ;
1042+ }
1043+ } ) ;
1044+ </ script >
1045+
10101046</ body >
10111047
10121048</ html >
0 commit comments