Text to speech converter with Javascript.
(Edited)
This is another short tutorial on how to build a text-to-speech converter. I used only 8 lines of code to get it done with JavaScript. I will improve on this in my next post and add more features to it.
Without delay, let's get to it.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Text to speech</title>
</head>
<body>
<div class="container">
<textarea name="" id="texts" cols="30" rows="10" placeholder="Enter some texts."></textarea>
<button id="submit" type="submit">Listen</button>
</div>
<script src="main.js"></script>
</body>
</html>
CSS
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background: #1a5252;
height: 100vh;
}
.container {
width: 70%;
max-width: 35em;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
background-color: #fff;
padding: 2em;
}
textarea {
font-size: 20px;
width: 100%;
padding: 1em;
border: 2px solid #1a5252;
}
#submit {
display: block;
width: 50%;
font-size: 20px;
position: relative;
margin: auto;
padding: 20px;
border: none;
background: #1a5252;
color: #fff;
cursor: pointer;
margin-top: 20px;
}
JS
The JS is pretty straight. I selected the html element and make the submit button to listen to click. Then I used the JavaScript SpeechSynthensisUtterance
constructor to get the content to convert to speech and used the speechSynthesis
to start the voice.
let txt = document.querySelector("#texts");
let submitBtn = document.querySelector("#submit");
submitBtn.addEventListener("click", ()=>{
let voiceMsg = new SpeechSynthesisUtterance(txt.value || "Enter some texts");
voiceMsg.voice = speechSynthesis.getVoices()[0];
console.log(voiceMsg)
speechSynthesis.speak(voiceMsg);
})
Result
Michael B, A.K.A Tykee, I am a software developer, writer and blockchain enthusiast. I write about finance, programming, tech and lifestyle. My contents are my opinions
0
0
0.000
NICE!!!
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.