使用.addEventListener结束

时间:2015-10-25 12:53:48

标签: javascript audio addeventlistener

以下代码旨在按顺序播放一系列短音频文件,如名为audio_sequence的javascript数组中所示。

.addEventListener('ended',function())用于触发序列中每个音频片段的播放。

这对数组中的前5个项目起作用,依次播放,但随后音频元素开始同时播放,序列变得混乱。

我尝试了几种不同的方法,都产生了类似的结果。 非常感谢任何见解。

可以在此处找到运行代码的示例: Play Sequence

这是javascript:

<script type="text/javascript">

var game_sounds = ["rooms", "bars", "food", "inveraray", "arse"];
var game_sequence = [0,1,2,3,4,0,1,2,3,4,0,1,2,3,4];    
var sequence_position = 0;

function play_next(){
    if (sequence_position < game_sequence.length){
        var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);                                                      
        audioElement.addEventListener('ended', function(){
            sequence_position++;
            play_next();
        }, true);
        audioElement.play();
    }
}

function playSequence(){
    sequence_position = 0;
    var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
//  alert(game_sounds[game_sequence[sequence_position]]);
    audioElement.addEventListener('ended', function(){
        sequence_position++;
        play_next();
    },true);
    audioElement.play();
}

</script>

&安培; html如下:

<a onClick="javascript:playSequence();" href="#"><h2>Play Sequence</h2></a>

<audio hidden id="rooms" preload="auto">
    <source src="/audio/rooms.mp3">
</audio>
<audio hidden id="food" preload="auto">
    <source src="/audio/food.mp3" >
</audio>
<audio hidden id="bars" preload="auto">
    <source src="/audio/bars.mp3">
</audio>
<audio hidden id="inveraray" preload="auto">
    <source src="/audio/inveraray.mp3">
</audio>
<audio hidden id="arse" preload="auto">
    <source src="/audio/arse.mp3">
</audio>

1 个答案:

答案 0 :(得分:0)

导致问题的原因是您将多个相同的事件侦听器附加到每个元素,因为它们处于循环中。在非常优雅但有效的解决方法中,您可以在再次附加之前删除侦听器:

var game_sounds = ["rooms", "bars", "food", "inveraray", "arse"];
var game_sequence = [0,1,2,3,4,0,1,2,3,4,0,1,2,3,4];    
var sequence_position = 0;

function play_next(){
    if (sequence_position < game_sequence.length){
        playSequence();
    }
}

function playSequence(){
    var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
//  alert(game_sounds[game_sequence[sequence_position]]);
    audioElement.removeEventListener('ended', prepareNextAudio);
    audioElement.addEventListener('ended', prepareNextAudio, true);
    audioElement.play();
}

function prepareNextAudio() {
    sequence_position++;
    play_next();
}

当每个音频播放三次时,此代码可以播放并停止播放列表,我想这就是你需要的。