Having trouble muting the audio on my Vue audio player

I'm facing some challenges with muting the audio within my vue app. I have a list of songs that can be played, paused, shuffled, etc., but I can't seem to get the mute function working. Here's what I have in the JavaScript:

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

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

And here is the computed method:

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

I've attempted adding the following:

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

In the music player, I have:

<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 initial attempt at creating a music player, and as someone new to this, I'm getting a bit overwhelmed by the JavaScript aspect. Any assistance would be greatly appreciated!

Answer №1

If you already have a reference to control the mute state of the player like this.audioPlayer in your example, you can create a method like this:

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

It's recommended by Vue not to use addEventListener for adding click listeners to HTML. Instead, follow Vue's guidelines (check out Vue docs).

I included a simple mute button beside the play button in this CodePen example: https://codepen.io/anon/pen/MLxOyj?editors=1111

In your case, setting this.audioPlayer is done like this:

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

VUE.js offers a cleaner way to reference elements:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

Tips for removing the default hover and click effects from a Material-UI CardActionArea

Check out the card sample with a lizard photo on https://material-ui.com/components/cards. When you hover over the cardActionArea, it will get darker or lighter based on the theme. Clicking on the card will make the picture change its brightness relative ...

Experimenting with an Angular Controller that invokes a service and receives a promise as a

I am currently in the process of testing an angular controller that relies on a service with a method that returns a promise. I have created a jasmine spy object to simulate the service and its promise-returning method. However, my mock promise is not retu ...

Having trouble with obtaining real-time text translation using ngx translate/core in Angular 2 with Typescript

Issue : I am facing a challenge with fetching dynamic text from a JSON file and translating it using the translate.get() method in Angular2. this.translate.get('keyInJson').subscribe(res => { this.valueFromJson = res; /* cre ...

When entering a sub-URL into the browser address bar, the routes do not display as expected

I am encountering an issue with navigating to different routes within my React application. While the home route is visible and functions properly when I start the app locally (npm run dev), I am unable to access other routes. No errors are displayed in t ...

Adjust the jQuery.animate function based on the specific value

When the button with the class name btn is clicked, the element with the class name img-box will transition with animation. I want to adjust the animation based on the current position of the img-box. After the first click on the button, the element mo ...

The error message states: "An attempt was made to destructure a non-iterable object. In order for non-array objects to be iterable, they must have a [Symbol.iterator

I need to call a RTK query endpoint from a function const [getCityCode, { isLoading, error, data, isSuccess, isError }] = useLocationQuery(); const getLocationDetails = async () => { const queryItems = { latitude: lat, longitude: long }; await getC ...

What is the best method for converting input files into FormData?

I recently created a form that allows users to upload both an audio file and an image file simultaneously. However, during testing, I noticed that the alert only displays basic data and does not include the form data. function PodcastUpload({ data }) { ...

What are the ideal scenarios for implementing React.Fragments?

Today I discovered React Fragments and their benefits. I learned that fragments are more efficient by reducing the number of tree nodes and improving cleanliness in the inspector. However, is there still a need to use div tags as containers in React compo ...

Generate a CSV file using Javascript

I am working with an HTML table (table id='testTable') and a button in the HTML code: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button> There is also JavaScript code involved: toCSV: func ...

Tips for including multiple JSON results into a single text box for auto-complete purposes

I am trying to combine different autocomplete list results into one text box. It's straightforward to use separate text boxes for different autocomplete results. HTML: <input id="university" name="university" type="text" /> <input id="unive ...

Creating numerous hash codes from a single data flow using Crypto in Node.js

Currently, I am developing a Node.js application where the readable stream from a child process' output is being piped into a writable stream from a Crypto module to generate four hash values (md5, sha1, sha256, and sha512). However, the challenge ari ...

Tips on how to retrieve the value of the second td in an HTML table when clicking on the first td utilizing jQuery

There is a specific requirement I have where I must retrieve the value of the second td in an HTML table when clicking on the first column. To accomplish this task, I am utilizing jQuery. $('.tbody').on('click','tr td:nth-child(1) ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

The asyncData function in Nuxt is throwing a surprise setTimeout (nuxt/no-timing-in-fetch-data)

Having trouble running a code on my pages/posts/index.vue page where I keep getting an error message 'Unexpected setTimeout in asyncData'. Can anyone provide assistance in understanding this error and suggest if any additional plugins are needed? ...

What is the best way to convert a series of sentences into JSON format?

I'm struggling with breaking down sentences. Here is a sample of the data: Head to the dining room. Open the cabinet and grab the bottle of whisky. Move to the kitchen. Open the fridge to get some lemonade for Jason. I am looking to format the outc ...

Error message: "The getJSON call is missing a semicolon before the statement."

Can someone please explain the following. I've been searching online for a long time trying to find assistance and I think I am following all the correct steps but still receiving errors. Here is the script in question on my webpage: function GetPag ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Puppeteer patiently waits for the keyboard.type function to complete typing a lengthy text

Currently, I am utilizing puppeteer for extracting information from a particular website. There is only one straightforward issue with the code snippet below: await page.keyboard.type(data) await page.click(buttonSelector) The initial line involves typin ...