Search code examples
javascriptvue.jshtml5-audio

Can't get audio to mute using vue audio player


I am struggling to get the audio to mute inside the vue app. I have an array of songs that will play, pause, shuffle etc. but cannot get the mute function working. I have the following in the js:

mute()
            {
            if (this.muted) {
                return this.volume = this.previousVolume;
            }

            this.previousVolume = this.volume;
            this.volume = 0;
        },

With this computed method:

muted() {
        return this.volume / 100 === 0;
}

I have tried adding this:

mutebtn = document.getElementById ("mutebtn")
              mutebtn.addEventListener ("click", mute());

With this in the music player:

<div id="mutebtn">
                  <i class="icon ion-ios-volume-high" title="Mute" v-if="volume" @click="mute()"></i>
                  <i class="icon ion-ios-volume-off" title="Unmute" v-if="muted" @click="volume"></i>
              </div>

This is my first attempt at making a music player and I'm new to all of this and getting confused with the javascript. Any help would be great!


Solution

  • In your example you already have a reference this.audioPlayer to control the mute state of the player.

    Therefore your method could look something like this:

    methods: {
        mute() {
          this.audioPlayer.muted = !this.audioPlayer.muted
        }
    }
    

    Please note - this is the way Vue recommends you to add something like click listeners to your HTML (see Vue docs). You should probably not use addEventListener for such a task.

    I added a simple mute button next to the play button: https://codepen.io/anon/pen/MLxOyj?editors=1111

    Another short hint for your example: You set this.audioPlayer like this:

    mounted () {
        this.audioPlayer = this.$el.querySelectorAll("audio")[0];
    }
    

    vue.js provides a cleaner way to reference elements:

    <audio src="my.mp3" ref="myAudio"></audio>
    
    mounted () {
        this.audioPlayer = this.$refs.myAudio;
    }