How to Use Your Microphone for Voice Input and Chat with ChatGPT Using JavaScript | by P N praveen | Nov, 2024
const startBtn = document.getElementById(‘startBtn’);
const outputDiv = document.getElementById(‘output’);
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = ‘en-US’; // Set the language to English (US)
// Start voice recognition when the button is clicked
startBtn.onclick = () => {
recognition.start();
outputDiv.textContent = ‘Listening…’; // Show that it’s listening
};
// When speech is recognized, display the recognized text
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript; // Get the transcript
outputDiv.textContent = `You said: ${transcript}`;
// Send the recognized text to ChatGPT (in the next step)
chatWithGPT(transcript);
};
// If there is an error in recognition
recognition.onerror = (event) => {
console.error(‘Speech recognition error: ‘, event.error);
outputDiv.textContent = ‘Error in speech recognition. Please try again.’;
};
// Automatically stop recognition when the user stops speaking
recognition.onend = () => {
outputDiv.textContent += ‘ (Stopped listening)’;
};
// Function to chat with ChatGPT using the recognized speech text
async function chatWithGPT(userInput) {
const apiKey = ‘YOUR_OPENAI_API_KEY’; // Replace with your OpenAI API key
const apiUrl = ‘https://api.openai.com/v1/completions’;
const requestBody = {
model: “text-davinci-003”, // or another model (e.g., gpt-3.5-turbo)
prompt: userInput,
max_tokens: 150,
temperature: 0.7
};
try {
const response = await fetch(apiUrl, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: `Bearer ${apiKey}`
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
outputDiv.textContent += `\nChatGPT: ${data.choices[0].text.trim()}`;
} catch (error) {
console.error(‘Error communicating with ChatGPT:’, error);
outputDiv.textContent += ‘\nFailed to get response from ChatGPT.’;
}
}
Read more here: Source link
