0

Here, I'm trying to convert the text to speech from django object and sorry to say that I don't know basic Js. Here is what I've tried.

Code

HTML

<p class="mb-1">{{ obj.reply }}</p>
<button class="btn btn-dark" onclick="txttospeech(obj.reply)">listen</button>

js

function txttospeech(txt) {
    var utterance  = new SpeechSynthesisUtterance();
    utterance.text = txt;
    speechSynthesis.speak(utterance);
}
1
  • in {{ obj.reply }} there are some texts. And I want to convert it in audio. Commented Mar 3, 2021 at 13:45

2 Answers 2

1

If you are trying to pass value of reply attribute to txttospeech function then you should do like this:

<button class="btn btn-dark" onclick="txttospeech({{ obj.reply }})">listen</button>

And if you want to cross verify whether value is actually getting passed. Then you can log in browser's console

function txttospeech(txt) {
    console.log("Value of reply attribute",txt);
    var utterance  = new SpeechSynthesisUtterance();
    utterance.text = txt;
    speechSynthesis.speak(utterance);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Uncaught SyntaxError: missing Uncaught ReferenceError
actually function is not working and it shows Uncaught SyntaxError: missing ) after argument list
0

you can replace onclick event with addEventListener, the following will get text from previous element or <p> as parameter for the .speak()

function txttospeech(txt) {
  var utterance = new SpeechSynthesisUtterance();
  utterance.text = txt;
  speechSynthesis.speak(utterance);
}

document.querySelectorAll('button.btn-dark').forEach(function(item) {
  item.addEventListener('click', function() {
    var textInput = this.previousElementSibling.textContent;
    txttospeech(textInput)
  })
})
<!--
<p class="mb-1">{{ obj.reply }}</p>
-->

<p class="mb-1">This is speech test</p>
<button class="btn btn-dark">listen</button>

<p class="mb-1">hello world</p>
<button class="btn btn-dark">listen</button>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.