Reputation: 111
I am trying to write a program that will take a sentence and play each word's sound clip. I am quite new to stackoverflow and javascript/html so I am sorry that this formatting is trash. I ran into the problem that the words just played together, and to fix this I added a .onended() but this only fixed it for the first two words and using a loop hasn't work. Thank you for any help. This is what I have currently:
<body>
What would you like me to say?
<input type="text" id="words"/>
<script>
document.getElementById('words').addEventListener('keypress', function (e) {
if (e.which === 13) {
var sentence = document.getElementById("words").value;
var splitted = sentence.split(" ");
var length = splitted.length;
var i = 1;
var sp = new Audio (splitted[0] + '.m4a');
sp.play();
sp.onended=function(){
if(i<length){
var sp = new Audio (splitted[i] + '.m4a');
sp.play();
i++;
}
}
}
});
And this is what I had before, when I looped them all and they all played together:
for(i=0;i<length;i++){
var sp = new Audio(splitted[i] + 'm4a');
sp.play();
}
Upvotes: 0
Views: 483
Reputation: 111
I have found a fix using a recursive function:
document.getElementById('words').addEventListener('keypress', function (e) {
if (e.which === 13) {
var sentence = document.getElementById("words").value;
var splitted = sentence.split(" ");
var length = splitted.length;
var i = 0;
testFunction();
function testFunction(){
if(i<length){
var sp = new Audio (splitted[i] + '.m4a');
sp.play();
i++;
sp.onended=function(){
testFunction();
}
}
}
}
});
Thank you for the help anyways!
Upvotes: 1
Reputation: 5
If I am right are you looking for text to speech. Then let me suggest you responsiveVoiceJS. This javascript library can take the data from your input field and can convert it to speech without you creating separate voice for each syllable. That's the easy way.
Resource: responsivevoice.org
Upvotes: 0
Reputation: 11364
When you created the audio for the next word, var sp = new Audio (splitted[i] + '.m4a')
, a new pristine Audio instance is created. Therefore, the second word doesn’t have the .onended
handler set. That’s why it only plays the first two words.
To fix, you have to add an ended
listener for each Audio that you create.
Upvotes: 0