仿微信音频播放vue组件

627 阅读1分钟
<template>
    <div id="voice" @click="playTo">
        <audio ref="audio" :src="soundurl"></audio>
        <img class="img_icon" src="../images/voice.png">
        <span class="time">{{long}} "</span>
        <i :class="['box',isPlay?'animate':'']"></i>
    </div>
</template>

<script>
export default {
    data() {
        return {
            isPlay:false
        };
    },
    props:{
        soundurl:{
            type:String,
            default:'',
        },
        long:{
            type:Number,
            default:0
        }
    },
    created() {

    },
    mounted() {

    },
    methods: {
        playTo(){
            this.$nextTick(()=>{
                const audio = this.$refs.audio;
                if(audio){
                    if(!this.isPlay){
                        this.isPlay = true;
                        audio.play();
                    }else{
                        audio.pause();
                        this.isPlay = false;
                    };
                    audio.addEventListener('ended', function () {  
                        this.isPlay = false;
                    }, false);
                };
            });
        }
    }
};
</script>

<style lang="scss">
#voice{
    position: relative;
    width: 100%;
    audio{
        display: none;
    }
    .img_icon{
        width: px2rem(15px);
        display: inline-block;
        vertical-align: middle;
        margin-right: px2rem(5px);
    }
    .time{
        vertical-align: middle;
        display: inline-block;
    }
    .box{
        position: absolute;
        top:0;
        left: px2rem(15px);
        width: px2rem(10px);
        height: 100%;
        background-color: #fff;
    }
    .animate{
        animation: leftTo 1.5s linear infinite;
    }
    @keyframes leftTo {
        0%{
            left: px2rem(5px);
        }
        50%{
            left: px2rem(10px);
        }
        100%{
            left: px2rem(15px);
        }
    }
}
</style>