this is tsx for astro shadcnui:
// src/components/VoiceAssistant.tsx
import React, { useState, useRef, useEffect } from "react";
import {
CardFooter,
CardDescription,
CardContent,
CardHeader,
Card,
} from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { PlayIcon, CircleStop, MessageCircle, XIcon } from "lucide-react";
import * as THREE from "three";
import { motion, AnimatePresence } from "framer-motion";
const api = "http://localhost:5000"; // Update this if deploying
const bgcolor = new THREE.Color().setHex(0x11161f);
const visualcolor = new THREE.Color().setHex(0x1d92c4);
// Function to initialize audio components after user gesture
const initializeAudio = async () => {
// Resume the AudioContext in response to a user gesture
const context = THREE.AudioContext.getContext();
if (context.state === "suspended") {
await context.resume();
}
code
if (audioRef.current && !analyser) {
const listener = new THREE.AudioListener();
listenerRef.current = listener;
const audio = new THREE.Audio(listener);
audio.setMediaElementSource(audioRef.current);
const newAnalyser = new THREE.AudioAnalyser(audio, 32);
setAnalyser(newAnalyser);
}
};
// Voice Recognition
useEffect(() => {
if (
!("webkitSpeechRecognition" in window) &&
!("SpeechRecognition" in window)
) {
console.error("Speech recognition not supported in this browser.");
return;
}
code
if (!recognitionRef.current) {
const SpeechRecognitionClass =
(window as any).SpeechRecognition ||
(window as any).webkitSpeechRecognition;
recognitionRef.current = new SpeechRecognitionClass();
recognitionRef.current.continuous = false; // Set to false to stop automatically
recognitionRef.current.interimResults = false;
recognitionRef.current.lang = "ar-SA"; // Change to your desired language
recognitionRef.current.onresult = (event: SpeechRecognitionEvent) => {
const transcript = Array.from(event.results)
.map((result) => result[0].transcript)
.join("");
console.log("Recognized speech:", transcript);
// Automatically send the recognized speech
handleSendMessage(transcript);
};
recognitionRef.current.onerror = (event: SpeechRecognitionErrorEvent) => {
console.error("Speech recognition error:", event.error);
};
recognitionRef.current.onend = () => {
if (isListening) {
recognitionRef.current?.start();
}
};
}
if (isListening) {
recognitionRef.current.start();
} else {
recognitionRef.current.stop();
}
// Clean up on unmount
return () => {
recognitionRef.current?.stop();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isListening]);
// Updated handler for toggling listening state
const handleToggleListening = async () => {
if (!isListening) {
await initializeAudio(); // Initialize audio on start
}
setIsListening(!isListening);
};
To enable continuous voice interactions where the application listens for user input after the AI responds via text-to-speech (TTS), you need to manage the state transitions between listening and talking seamlessly. Below is a comprehensive guide on how to achieve this, along with the necessary code modifications.
Overview of the Implementation Steps
Introduce a voiceChatEnabled State:
This state will toggle the entire voice chat functionality on or off.
Manage Listening State During Interaction:
When the AI is about to respond (i.e., TTS starts), pause the listening to prevent conflicts.
After the AI finishes speaking, automatically resume listening if voiceChatEnabled is active.
Update UI Controls:
Ensure the UI reflects the current state, allowing users to enable or disable voice chat as needed.
Step-by-Step Implementation
1. Introduce a voiceChatEnabled State
Add a new state to manage whether the voice chat loop (listen → respond → listen) is active.
When voiceChatEnabled is active, disable manual input to prevent conflicts between voice and text inputs.
tsx
<Input
placeholder="Type a message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSendMessage(input)}
disabled={voiceChatEnabled} // Disable manual input while voice chat is active
/>
<Button
onClick={() => handleSendMessage(input)}
className="ml-2 text-foreground"
disabled={voiceChatEnabled} // Disable manual send while voice chat is active
>
Send
</Button>
Final Updated Component
Here's the complete updated VoiceAssistant component with the changes integrated:
tsx
Explanation of the Changes
Voice Chat State (voiceChatEnabled):
This new state controls whether the voice chat loop is active.
When enabled, the system listens for user input, sends it to the AI, plays the AI's response via TTS, and then resumes listening automatically.
Toggle Handler (toggleVoiceChat):
This function toggles the voiceChatEnabled state.
It starts listening when enabled and stops listening when disabled.
Speech Recognition Effect:
The useEffect hook now listens to both isListening and voiceChatEnabled.
When onend is triggered in speech recognition and voiceChatEnabled is active, it automatically restarts listening, enabling continuous interaction.
Sending Messages (handleSendMessage):
Before sending a message, the system stops listening to prevent capturing the AI's response.
After the AI responds via TTS, the onended handler resumes listening if voice chat is still enabled.
UI Adjustments:
The voice chat toggle button now reflects the voiceChatEnabled state.
Manual input fields (Input and Send buttons) are disabled when voice chat is active to avoid conflicts between voice and text inputs.
Final Notes
User Experience:
With these changes, users can enable voice chat to have a seamless, hands-free conversation with the AI.
The system ensures that after each AI response, it automatically listens for the next user input without requiring manual intervention.
Error Handling:
Ensure that the browser supports the Web Speech API for speech recognition.
Provide fallback methods or notifications if speech recognition is not supported.
Customization:
Adjust the speech recognition language (recognitionRef.current.lang) as needed.
Fine-tune the UI components to match your application's design requirements.
By following these steps and implementing the provided code changes, your VoiceAssistant component will support continuous voice interactions, enhancing the user experience by allowing seamless voice-based conversations.