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

查看:798
本文介绍了javascript - 使用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() 把自己回调函数移除掉.

这篇关于javascript - 使用addEventListener监听audio的ended事件,会重复执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆