In this project we will discuss about the method of using speech recognition in HTML CSS And PHP Project.
Speech Recognition Initialization:
var recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.msSpeechRecognition)();
This line creates a new instance of the SpeechRecognition
object, which is supported by different browser-specific implementations (e.g., webkitSpeechRecognition
for Chrome).
Default Configuration:
recognition.lang = 'en-US'; // Default language
recognition.interimResults = false;
recognition.maxAlternatives = 1;
These lines set the default properties for the recognition
object:
lang
: The language for speech recognition is set to US English.interimResults
: Whenfalse
, it ensures that only final results are returned, not intermediate results.maxAlternatives
: Limits the number of alternative recognition results to 1.
Language Change Event Listener:
document.getElementById('language').addEventListener('change', function() {
recognition.lang = this.value;
});
This part adds an event listener to an HTML element with the id language
. When the value of this element changes (e.g., when a user selects a different language from a dropdown menu), the recognition.lang
property is updated to the new value.
Start Recording Function:
function startRecording() {
console.log('Start recording');
recognition.start();
}
This function starts the speech recognition process. When called, it logs “Start recording” to the console and then calls the start
method on the recognition
object.
Stop Recording Function:
function stopRecording() {
console.log('Stop recording');
recognition.stop();
}
This function stops the speech recognition process. When called, it logs “Stop recording” to the console and then calls the stop
method on the recognition
object.
Complete Javascript Code
var recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.msSpeechRecognition)();
recognition.lang = 'en-US'; // Default language
recognition.interimResults = false;
recognition.maxAlternatives = 1;
document.getElementById('language').addEventListener('change', function() {
recognition.lang = this.value;
});
function startRecording() {
console.log('Start recording');
recognition.start();
}
function stopRecording() {
console.log('Stop recording');
recognition.stop();
}
recognition.onresult = function(event) {
var speechResult = event.results[0][0].transcript;
console.log('Recognition result:', speechResult);
document.getElementById('userMessage').value = speechResult;
// Call the function that handles the form submission
handleSubmit();
};