如何使用JavaScript循环遍历多个音频文件并按顺序播放它们?

7
当点击按钮时,我想播放四个音频,其中三个来自兄弟ID,最后一个来自所点击的ID。请帮我解决这个问题。
我已经更改了代码,但是音频仍然没有按顺序播放。最后一个音频先播放,然后是第二个和第三个音频,它们之间的间隔不够长。
$(document).on('click', '.phonics_tab .audioSmImg_learn', function () {
    var PID = '#' + $(this).parents('.phonics_tab').attr('id');
    audioFileName = 'audio/' + $(this).attr('id') + '.mp3';
    var audioElmnt = {};
    var audioFileName1 = {};

    $(PID + ' .word_box_item').each(function (inx, i) {
        if (inx >= 1) {
            audioElmnt[inx - 1].pause();
            audioElmnt[inx - 1].currentTime = 0;
        }
        audioElmnt[inx] = document.createElement('audio');
        audioElmnt[inx].setAttribute('autoplay', 'false');
        audioFileName1[inx] = 'audio/' + $(this).children('h2').attr('id') + '.mp3';
        audioElmnt[inx].setAttribute('src', audioFileName1[inx]);
        audioElmnt[inx].load();

         //in previous code your inx only run for the last item.
        playAudio(audioElmnt[inx], 300); // here the object will be sent to the function and will be used inside the timer.
    });

    function playAudio(audioElmnt, delay){
        setTimeout(function () {
            audioElmnt.play();
        }, delay);
    }   

    setTimeout(function () {
        audioElement.currentTime = 0;
        audioElement.pause();
        audioElement.setAttribute('src', audioFileName);
        audioElement.load();
        audioElement.play();
    }, 500);
});
2个回答

1
你不应该在循环内部使用setTimeout,它与其他编程语言的行为不同。你的解决方案应该像这样。 在之前的代码中,你的变量inx只运行最后一个项目。

$(document).on('click', ' .audioImg', function () {
    var ParentID = '#' + $(this).parents('.parent').attr('id');
    audioFileName = 'audio/' + $(this).attr('id') + '.mp3';
    var audioElmnt = {};
    var audioFileName1 = {};

    $(PID + ' .item').each(function (inx, i) {
        if (inx >= 1) {
            audioElmnt[inx - 1].pause();
            audioElmnt[inx - 1].currentTime = 0;
        }

        audioElmnt[inx] = document.createElement('audio');
        audioElmnt[inx].setAttribute('autoplay', 'false');
        audioFileName1[inx] = 'audio/' + $(this).children('h2').attr('id') + '.mp3';
        audioElmnt[inx].setAttribute('src', audioFileName1[inx]);

        audioElmnt[inx].load();

       //in previous code your inx only run for the last item.
        playAudio(audioElmnt[inx], 150); // here the object will be sent to the function and will be used inside the timer.

    });
    var playAudio = function(audioElmnt, delay){
       setTimeout(function () {
            audioElmnt.play();
        }, delay);
    }
    setTimeout(function () {
        audioElement.currentTime = 0;
        audioElement.pause();
        audioElement.setAttribute('src', audioFileName);
        audioElement.load();
        audioElement.play();
    }, 500);
});


0

音频标签有一个事件,你可以监听它

audio.addEventListener('ended',function(e){ 
});

在结束信号被发出后,您可以开始列表中的下一个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接