使用addEventListener监听audio的ended事件,会重复执行?

<template>
    <div>
        <audio :src="nowMusicUrl" controls="controls" ref="musicClick"></audio>
        当前播放的曲目是{{nowMusicName}}
        <input type="button" value="试试播放嘿" @click="playMusic">
    </div>
</template>
<script type="text/ecmascript-6">
    export default{
        data(){
            return {
                nowMusicUrl:'',
                nowMusicName:'',
                startIndex : 0
            }
        },
        props:{
            musicList:{
                type: Array,
                default() {
                    return [];
                }
            }
        },
        created() {
            this.nowMusicUrl = this.musicList[this.startIndex].location;
            this.nowMusicName = this.musicList[this.startIndex].musicname;
        },
        mounted:function(){
            console.log('dom渲染完毕')
            this.playMusic(this)
        },
        methods: {
            playMusic:function(that){
                console.log(that.musicList.length,that.startIndex);
                if (that.startIndex === that.musicList.length ) {
                    that.startIndex = 0;
                }
                that.nowMusicUrl = that.musicList[that.startIndex].location;
                that.nowMusicName = that.musicList[that.startIndex].musicname;
                let musicPl = this.$refs.musicClick;
                setTimeout(function(){
                    musicPl.play();
                },1000);

                musicPl.addEventListener('ended',function(){
                    console.log('音乐播放完毕');
                    that.startIndex = that.startIndex+1;
                    that.playMusic(that);

                },false)
            }
        }
    }
</script>

第一次监听音乐结束后 打印1次音乐播放完毕 ,第二次2次,第三次4次, 第4次8次。 如何解决,谢谢大佬们了~

回答:

监听时间不要在 PlayMusic 方法里面执行, 应该在初始化 Audio 对象时绑定一次即可.

如果非要在 PlayMusic 方法里面绑定的话, 在回调函数执行时, 执行 audio.removeEventListener() 把自己回调函数移除掉.

回答:

因为addEventListener绑定多个handler是不会覆盖的,事件绑定的东西应该放在生命周期中去做。

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注