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

use*_*358 7 javascript audio jquery html5

点击一个按钮,我想播放4个音频,三个来自兄弟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);
});
Run Code Online (Sandbox Code Playgroud)

小智 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);
});
Run Code Online (Sandbox Code Playgroud)