Converting text to speech using HTML, CSS, and JavaScript can be done using the SpeechSynthesis API.
The SpeechSynthesis API is a built-in JavaScript API that allows you to convert text to speech directly in the browser without the need for any external libraries.
Here is an example of how to use the SpeechSynthesis API to convert text to speech in HTML, CSS, and JavaScript:
HTML Code
id="text-to-speech">
CSS Code
#text-to-speech {
display: flex;
flex-direction: column;
align-items: center;
}
#text {
width: 300px;
height: 100px;
padding: 10px;
margin-bottom: 10px;
}
#speak-button {
padding: 10px;
font-size: 18px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
JavaScript Code
// Get the text area and speak button elements
let textArea = document.getElementById("text");
let speakButton = document.getElementById("speak-button");
// Add an event listener to the speak button
speakButton.addEventListener("click", function() {
// Get the text from the text area
let text = textArea.value;
// Create a new SpeechSynthesisUtterance object
let utterance = new SpeechSynthesisUtterance();
// Set the text and voice of the utterance
utterance.text = text;
utterance.voice = window.speechSynthesis.getVoices()[0];
// Speak the utterance
window.speechSynthesis.speak(utterance);
});
This example creates a text area and a button in the HTML, styles them using CSS, and then uses JavaScript to add an event listener to the button that converts the text in the text area to speech when the button is clicked.
This is just a basic example and you can customize it further according to your needs by, for example, adding more options to the speech synthesis and also you can use libraries such as responsivevoice.js, meSpeak.js or annyang.js to add more functionalities and features.