3

As a beginner, I was making a text-to-speech project.

Now it's working fine, But I want to change the input with p, div, or others tags.

That means I want to replace (input tag) with others. Now how can I do that?

And also I want to remove the (select tag) option as my wish. Help me kindly.

var txtInput = document.querySelector('#txtInput');
var voiceList = document.querySelector('#voiceList');
var btnSpeak = document.querySelector('#btnSpeak');
var synth = window.speechSynthesis;
var voices = [];

PopulateVoices();
if (speechSynthesis !== undefined) {
  speechSynthesis.onvoiceschanged = PopulateVoices;
}

btnSpeak.addEventListener('click', () => {
  var toSpeak = new SpeechSynthesisUtterance(txtInput.value);
  var selectedVoiceName = voiceList.selectedOptions[0].getAttribute('data-name');
  voices.forEach((voice) => {
    if (voice.name === selectedVoiceName) {
      toSpeak.voice = voice;
    }
  });
  synth.speak(toSpeak);
});

function PopulateVoices() {
  voices = synth.getVoices();
  var selectedIndex = voiceList.selectedIndex < 0 ? 0 : voiceList.selectedIndex;
  voiceList.innerHTML = '';
  voices.forEach((voice) => {
    var listItem = document.createElement('option');
    listItem.textContent = voice.name;
    listItem.setAttribute('data-lang', voice.lang);
    listItem.setAttribute('data-name', voice.name);
    voiceList.appendChild(listItem);
  });

  voiceList.selectedIndex = selectedIndex;
}
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>

  Select Voice:
  <select id='voiceList'></select> <br><br>

  <input id='txtInput' /> <br><br>
  <button id='btnSpeak'>Speak!</button>

</body>

5
  • 1
    If you want users to be able to type something in a field and then have it spoken, the best thing is an input tag. The other tags would be read only.
    – lharby
    May 29, 2022 at 9:18
  • You can remove the select but you would have to manually assign one of the voices in the dropdown list as a default
    – lharby
    May 29, 2022 at 9:19
  • Yes, I just want to be read. How can I do that?
    – FERDAUS SK
    May 29, 2022 at 9:32
  • Also, I want to manually assign one. how have to do?
    – FERDAUS SK
    May 29, 2022 at 9:34
  • I have an answer for you, I will update soon.
    – lharby
    May 30, 2022 at 11:29

1 Answer 1

1

OK, the code I have written is much simpler. I will try to explain:

HTML:

    <p id="txtInput">Speak this text</p> // change to paragraph element but keep the same ID
    <button id='btnSpeak'>Speak!</button>

JavaScript:

        var txtInput = document.querySelector('#txtInput');
        var btnSpeak = document.querySelector('#btnSpeak');
        var synth = window.speechSynthesis;
        var voices = [];

        PopulateVoices();
        if(speechSynthesis !== undefined){
            speechSynthesis.onvoiceschanged = PopulateVoices;
        }

        btnSpeak.addEventListener('click', ()=> {
            var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);
            toSpeak.voice = voices[7]; // Spanish
            synth.speak(toSpeak);
        });

        function PopulateVoices(){
            voices = synth.getVoices();
            voices.forEach((item, index) => console.log(item.name, index));
        }

Main things to note, I changed the input to a paragraph element but assigned it the same ID (this means that the name of the ID and element no longer really make sense txtInput for a paragraph etc, but that is academic). Only one ID should exist in the DOM at any one time, so make sure you remove the other element if it is a duplicate or you can change the ID of the element and update the js selector like so

<p id="foo">Text</a>

var elementID = document.querySelector('#foo');

In the previous function you are getting the value of the input text using:

var toSpeak = new SpeechSynthesisUtterance(txtInput.value);

Because the paragraph element does not have a value attribute we change this to:

var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);

Which will return the inner text content.

I get the array of voices from the API, and for debugging purposes I am console logging all the the voice names and indices:

voices.forEach((item, index) => console.log(item.name, index));

Which returns for example:

Microsoft David - English (United States) 0
Microsoft Mark - English (United States) 1
Microsoft Zira - English (United States) 2
...

This shows me each voice in the console, for now I have set index 7 (which is Google español) as the preset voice. You will have to update the index for the voice that you want in:

toSpeak.voice = voices[7]; // Spanish

I hope this makes sense, the code is now mixing ES5 style syntax (and older) with more modern versions, which is not my preference, but this should work as expected.

There is also a jsfiddle you can experiment with

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.