简体   繁体   中英

How to play one track after other with <audio> tag in HTML5 using JS/jQuery?

In an attempt to overcome Google TTS API's character limit of 100 chars, tried to loop every 100 characters to fetch a fresh mp3 from the api and play seamlessly. Tried multiple ways, but the .play() and the event listeners like canplay/onended doesn't just seem to work inside a loop! Best that could be achieved is to get all the downloaded tracks to play simultaneously, rather than one after the other. Below is some code :-

if ($("#theinput").attr("value").length > 100){
var len = $("#theinput").attr("value").length;
alert(len);
var audioPlayer = document.getElementById("spokenmemory");    
for (var i=0; i < (len / 100); i++) {
var stl=i*100;
var str = $("#theinput").attr("value").substr(stl, 100);
$("#spokenmemory").attr("src", "http://translate.google.com/translate_tts? tl=en&q="+str);
alert(str);
audioPlayer.load();  
audioPlayer.addEventListener('canplay', function () {
              alert('Loaded');
              audioPlayer.play();
            } );
//audioPlayer.play(); 

            }

Any help will be appreciated.

Try to use the trigger function instead

fadeInAudio : function(audio){
//      audio.play();
    audio.trigger("play");
},

fadeOutAudio : function(audio){
//      audio.pause();
    audio.trigger("pause");
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM