JS/JQuery text to speech: How to chain audios?

不羁岁月 提交于 2019-12-06 14:36:57

Something like this :

$('#play').data('audio', $('audio:first')).on('click', function() {
    var self = this;
    $(this).data('audio').on('ended', function() {
        var n = $('audio').eq( $(self).data('audio').index('audio') + 1 );
        $(self).data('audio', n.length ? n : $('audio:first'));
    }).get(0).play();
});

FIDDLE

It gets the first audio element in the document, and stores it in jQuery's data, and once it's played (the onended event) it get's the next audio element in the DOM and the next time the button is clicked, it playes that, and when there are no more audio elements, it starts from the beginning again.

If you really wan't to use the ID instead, it would be something like :

var audio = 1

$('#play').on('click', function() {
    $('#id' + audio).get(0).play();
    audio++;
});

FIDDLE

To play all three on a single click, one after the other, you'd do

$('#play').on('click', function() {
    $('audio').on('ended', function() {
        $('audio').eq($(this).index('audio')+1).get(0).play();
    }).get(0).play();
});

FIDDLE

No jQuery needed, just listen for the ended event

The simple case is the following:

document.getElementById('id1').addEventListener('ended', function(){
    document.getElementById('id2').play();
});   

Abstracted, it would look like http://jsfiddle.net/J9wAB/13/

function chain(ids/* id, id, ... */) {
    function setHandler(first, next) {
      document.getElementById(first).addEventListener('ended', function(){
        document.getElementById(next).play();
      });   
    }
    for (var i = 0; i < arguments.length - 1; i++) {
        setHandler(arguments[i], arguments[i+1]);
    }
}
chain('id1', 'id2', 'id3');
Joost

You can use the onended="yourcallback()" to start the next audio.

Look at this answer please: https://stackoverflow.com/a/7652194/2707424

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!