Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript play audio one after another HTML5

I have a problem with playing audio from a dynamically created javascript audio object one after another. 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 do this by an event listener, or is there any other way? It is not just about Google, so I would like to ask you for a general solution, not a ready made google speech script.

Could you help me? How can I play the audio one after another?

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 the Eventlistener, I guess it should work like this, but I still hae a problem that the Eentlistener does not fire if this is the first file played, right?

I would be happy for further support.

Thank you in advance.

like image 917
Owenir Avatar asked Dec 08 '14 17:12

Owenir


People also ask

How do I use next audio in JavaScript?

on('click', PLAYER. next); And it will do the trick.

How can I play one audio at a time in HTML?

addEventListener("DOMContentLoaded", function() { onlyPlayOneIn(document. body); });

How play audio with JavaScript and HTML?

play() to Play Audio Files in JavaScript. We can load an audio file in JavaScript simply by creating an audio object instance, i.e. using new Audio() . After an audio file is loaded, we can play it using the . play() function.

How do you Autoplay a song in JavaScript?

Use the autoplay attribute on your audio element. Also, try to prefer using the Audio() constructor when generating an Audio element in JavaScript. Lastly, don't call audio. load() here, setting the src value in this case triggers that automatically.


1 Answers

There is an ended event, you can change the src property in a listener for it.

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++;
    }
};
like image 163
tachyonflux Avatar answered Sep 27 '22 19:09

tachyonflux