I want to create a script in javascript/jquery that play’s/speaks the letters of a certain word in the background.
when i call the function playWord(); It spells out the letters of a word in a div.
For example, the word ‘help’. It should spell: ‘h’ ‘e’ ‘l’ ‘p’. Each letter has an .mp3 file.
Before the next letter spells, it has to wait untill the letter is fully spelled.
This is what i have so far, but its not properly. Sometimes the time in between letters is like 5 seconds.
<script type='text/javascript'>
var letterCounter = 0;
//the letter speed in ms
var spellAudioSpeed = 1000;
function playWord(){
letterCounter = 0;
//the word from the div
playLetters($('#transWord').text().toLowerCase());
}
function playLetters(pWord){
if(letterCounter < pWord.length){
var letter = pWord.charAt(letterCounter);
//create an new audio element
var audioElement = document.createElement('audio');
if(letter == ' '){
audioElement.setAttribute('src', 'Letters/spatie.mp3');
} else if(letter == '\''){
audioElement.setAttribute('src', 'Letters/aanhalingsteken.mp3');
} else if(letter == '\\"'){
audioElement.setAttribute('src', 'Letters/dubbeleaanhalingsteken.mp3');
} else if(letter == '/'){
audioElement.setAttribute('src', 'Letters/schuinestreep.mp3');
} else if(letter == '\\'){
audioElement.setAttribute('src', 'Letters/schuinestreepachteruit.mp3');
} else {
audioElement.setAttribute('src', 'Letters/'+letter+'.mp3');
}
//couldnt find a better way to determine the duration.. ???
audioElement.addEventListener('durationchange', function() {
audioElement.play();
letterCounter++;
timeOut = setTimeout(function(){playLetters(pWord)},
spellAudioSpeed + (audioElement.duration * 1000));
}, true);
} else if (letterCounter == pWord.length){
//do stuff
alert("finished");
}
}
playWord();
Try using the preload attribute.