JavaScript play audio one by one HTML5

I have a problem playing audio from a dynamically generated javascript audio object one by one. The audio comes from Google over an array of strings.

for (i = 0; i < Txt_array.length; i++) {
audio.src ='http://translate.google.com/translate_tts?&tl=en&q='+Txt_array[i];
audio.play();};

      

I would like to make this an event listener, or is there another way? It's not just about Google, so I would like to ask you for a general solution, not a ready-made speech-to-speech script.

could you help me? How to play sound one by one?

Update:

audio.src='http://translate.google.com/translate_tts?&tl=en&q=' + Txt_array[0];
audio.play();

audio.addEventListener('ended', function(){
for (i = 1; i < Txt_array.length; i++) {
audio.src ='http://translate.google.com/translate_tts?&tl=en&q='+Txt_array[i];
audio.play();};
}, false);

      

I added an Eventlistener, I think it should work like this, but I still have the problem that the Eentlistener won't fire if it's the first file, right?

I would be glad for further support.

Thanks in advance.

+3


source to share


1 answer


There is an end event , you can change the property src

in it to listen.



var strings = "Hello how are you".split(" ");
var index = 1;

audio.src='http://translate.google.com/translate_tts?&tl=en&q=' + strings[0];
audio.play();

audio.onended = function() {
    if(index < strings.length){
        audio.src='http://translate.google.com/translate_tts?&tl=en&q=' + strings[index];
        audio.play();
        index++;
    }
};

      

+4


source







All Articles