Text to Speech Converter using JavaScript

text to speech converter using javascript by sparkify solutions

Learn how to create a functional text to speech converter using HTML, CSS and JavaScript.

  • Use HTML to structure the text to speech converter app.
  • Use CSS to style the text to speech converter app.
  • For the functionality of text to speech converter use JavaScript.

The source code for this project is available for download by clicking ‘Download Now’ or cloning the GitHub repository.

Source code of HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text to Speech Converter</title>
    <link rel="stylesheet" href="style.css">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <script src="script.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Text To Speech <span>Converter</span></h1>
        <textarea placeholder="Write anything here...."></textarea>
        <div class="row">
            <select></select>
            <button><i class='bx bx-play'></i> Listen</button>
        </div>
    </div>
</body>
</html>

Explanation

Body:

<body> section holds the content which is to be displayed on web page.

  • Container: <div class=”container”> sets a container element (generally a div) with a class named “container”. This is likely used to group the entire text-to-speech converter interface within it.
  • Heading: <h1>Text To Speech <span>Converter</span></h1> sets the main heading of the application using an h1 tag. The <span> element with the text “Converter” is styled differently within the CSS to potentially emphasize it.
  • Text Input: <textarea placeholder=”Write anything here….”></textarea> creates a multi-line text area where the user can enter the text they want to convert to speech and the attribute is a place holder attribute that gives the user an indication of what to type in.
  • Row: <div class=”row”> defines another container element (likely a div) with a class name of “row”. This might be used for layout purposes within the CSS, possibly arranging the dropdown and button horizontally.
  • Dropdown (Optional): <select></select> This element suggests a potential dropdown menu. That is used for selecting voice options.
  • Button: <button><i class=’bx bx-play’></i> Listen</button> creates a button with the text “Listen”. The use of the <i class=’bx bx-play’></i> element simply indicates tells a “play” icon, which has been imported from “boxicons” library.. When the user clicks this button, the JavaScript code will likely trigger the text-to-speech conversion.

Script Deferral:

  • <script src=”script.js” defer></script> This line is used to establish connection between the HTML document and external JavaScript file, which is “script.js”. The defer attribute instructs the browser that the script will be run after the HTML parsing is complete. This ensures the page structure is fully rendered first, avoiding potential issues where the JavaScript might rely on elements that haven’t been loaded yet.

Source code of CSS file

*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
.container{
width: 100%;
min-height: 100vh;
background: linear-gradient(45deg , #00098b , #37014d);
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.container h1{
color: #fff;
font-size: 40px;
font-weight: 500;
letter-spacing: 1px;
margin-top: -50px;
margin-bottom: 50px;
}
.container h1 span{
color: #ff00aa;
font-size: 42px;
}
textarea{
width:550px;
height: 250px;
background: #403d84;
color: #fff;
font-size: 18px;
border: 0;
outline: 0;
padding: 20px;
border-radius: 10px;
resize: none;
margin-bottom: 30px;
}
textarea::placeholder{
font-size: 18px;
letter-spacing: 2px;
color: #ddd;
}
.row{
width: 550px;
display: flex;
align-items: center;
gap: 20px;
}
select{
flex: 1;
color: #fff;
background: #403d84;
height: 45px;
padding: 0 20px;
outline: 0;
border: 0;
border-radius: 35px;
appearance: none;
}
button{
background: #ff00aa;
color: #fff;
font-size: 18px;
letter-spacing: 1px;
padding: 10px 30px 10px 45px;
border-radius: 35px;
border: 0;
outline: 0;
cursor: pointer;
position: relative;
}
button i{
font-size: 35px;
position: absolute;
left: 10px;
top: 2px;
}

Explanation

General Structure and Styling:

  • Reset Styles: *{padding: 0; margin: 0; box-sizing: border-box;} ensures consistent styling across elements by resetting default browser-specific styles.
  • Container: .container sets the overall layout, centering the content vertically and horizontally. The background property applies a gradient for a visually appealing background.
  • Heading: .container h1 styles the main heading with color, font size, weight, letter spacing, and margins. The span element within the heading allows for different styling of the word “Converter”.

Text Area:

  • textarea styles the text area where the user enters the text to be converted. It includes properties for width, height, background color, font size, border, outline, padding, border radius, and resizing. The ::placeholder pseudo-selector styles the placeholder text within the textarea.

Row and Dropdown:

  • .row defines a container for the dropdown and button, ensuring they are aligned horizontally.
  • select styles the dropdown element, including properties for flexibility, color, background, height, padding, outline, border, border radius, and appearance.

Button

  • button styles the “Listen” button, including properties for background color, font size, letter spacing, padding, border radius, border, outline, cursor, and position. The i element within the button is used to display the “play” icon.

Source code of JavaScript file

let speech = new SpeechSynthesisUtterance();
let voices = [];
let voiceSelect = document.querySelector("select");
window.speechSynthesis.onvoiceschanged = () =>{
    voices = window.speechSynthesis.getVoices();
    speech.voice = voices[0];
    voices.forEach((voice , i) => (voiceSelect.options[i] = new Option(voice.name , i)));
};
voiceSelect.addEventListener("change" , ()=>{
    speech.voice = voices[voiceSelect.value];
});
// Event listener for button click (to speak the text)
document.querySelector("button").addEventListener("click", function(){
    speech.text = document.querySelector("textarea").value;
    window.speechSynthesis.speak(speech);
  });

Explanation

1. Variables and Initialization:

  • let speech = new SpeechSynthesisUtterance();: Invokes a constructor of the SpeechSynizationUtterance and assigns the invoked constructor to the name of the object ‘speech’. It contains variables associated with the text that has to be spoken including the text, voice, pitch, rate and so on.
  • let voices = [];: Initializes an empty array named voices to store available voices later.
  • let voiceSelect = document.querySelector(“select”);: Selects the select element (dropdown) from the HTML document and assigns it to the voiceSelect variable. This variable will be used to populate the dropdown with available voices.

2. Handling Voice Availability:

  • window.speechSynthesis.onvoiceschanged = () => {…};: Appends an event handler to the onvoiceschanged event of window.speechSynthesis. This event occurs any time the available voices change (this normally happens when the page is loading for the first time).
  • Inside the event listener:
    • voices = window.speechSynthesis.getVoices();: invokes getVoices() method to retrieve all the available voices and stores them in the voices array.
    • speech.voice = voices[0];: A function that is used for setting the initial voice for the speech object as the first value within the voices array in case there are some voices available.
    • voices.forEach((voice, i) => (voiceSelect.options[i] = new Option(voice.name, i)));: Loops through each voice in the voices array:
      voice.name: Accesses the name of the current voice.
    • i: Represents the index of the current voice in the array.
    • voiceSelect.options[i] = new Option(voice.name, i);: Creates a new <option> element for the dropdown.
    • voice.name: Sets the text displayed in the dropdown option.
    • i: Sets the value of the option, corresponding to the index of the voice in the voices array (used for selecting the right voice later).

3. Voice Selection Using Dropdown:

  • voiceSelect.addEventListener(“change”, () => {…});: Attaches an event listener to the change event of the voiceSelect element (dropdown). This event fires whenever the user selects a different voice option.
  • Inside the event listener:
    • speech.voice = voices[voiceSelect.value];: Sets the voice property of the speech object to the voice corresponding to the selected option’s value. This value matches the index of the voice in the voices array.

4. Speaking the Text:

This section is likely placed outside of any functions or event listeners:

  • document.querySelector(“button”).addEventListener(“click”, function(){ … });: Includes an event handler for the click event of the button.
  • Inside the event listener:
    • speech.text = document.querySelector(“textarea”).value;: Returns the text that has been typed in textarea and stores it in the text field of the speech object. This sets the text that will be spoken.
    • window.speechSynthesis.speak(speech);: Sends a speak() method of the window.speechSynthesis object by using the speech as an argument. This triggers the browser to speak the text using the configured properties.

Thanks for reading this article text to speech converter using javascript by Sparkify Solutions

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top