Is there a way to stop a music track from playing?

function playMusic(){
    var music = new Audio('musicfile.mp3');

    if (music.paused) {
        music.play();
    } else {
        music.pause();
    }
}

<input type="button" value="sound" onclick="playMusic()" />

When I click on the sound button, it plays the music. However, if I click on it again, it plays the music twice. I am searching for a solution to enable playing and pausing the music with one button press. Thank you.

Answer №1

Below you'll find a code snippet for a click-activated music player.

let clickCount = 0;
  var audioClip = new Audio('http://freshly-ground.com//data/audio/mpc/20151115%20-%20Mashmakhan%20Beat%20-%20The%20Orchestra%20%28Dynamic%20Compressor%201.2.6%29.mp3');
  
  function playAudio() {
    audioClip.play();
  }

  function pauseAudio() {
    audioClip.pause();
  }

  function toggleAudio() {
    if (clickCount == 0) { 
      playAudio();
      console.log('music playing');
      clickCount = 1;
    } else {
      pauseAudio();
      console.log('music paused');
      clickCount = 0;
    }
  }
<input type="button" value="audio" onclick="toggleAudio()"/>

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

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

transferring a webpage to a collaborative platform

We currently have an intranet with numerous html pages and various attachments such as .doc and .xls files. We are contemplating migrating all of this to Confluence WIKI. Is there any script or automated tool available that can assist us in this migratio ...

Displaying the information fetched using axios on the screen using node.js

Is there a way to display the information from the input boxes in the image on the screen using node js? ...

Updating the variables of HTML components using JavaScript after making an AJAX request

I am using ajax to fetch a list of user data. But after this ajax call, I need to display the data in an HTML structure like a datasheet for each user. My question is how can I store the HTML code in a functional and elegant way to maintain readability and ...

CSRF token not recognized. Request cancelled. Even after including the CSRF token {% csrf_token %}, the error persists

I'm encountering an issue with the CSRF token being incorrect or invalid. I have included the {% csrf_token %} above my form, but I am still facing this problem. Can anyone assist me with this? Here is a snippet of my HTML file: <h4>regist ...

Articles related to Express.js - encountering issues when attempting to read properties from a null object

I'm trying to display related articles based on categories using Mongoose for querying data from MongoDB. However, when I attempt the code below, I encounter an error message stating "TypeError: Cannot read properties of null (reading 'category& ...

Having difficulty with closing a modal using v-model in VueJS

Upon pressing the button labeled Close, an error message appeared in the console as shown below: "Error: Cannot find module './undefined'" found in ---> <WhatsNew> at src/components/WhatsNew.vue Displayed below is the conten ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

Finding elements based on their class can be accomplished by using XPath

Can you show me how to effectively utilize the :not selector to choose elements in a scenario like this: <div class="parent"> <div class="a b c"/> <div class="a"/> </div> I am trying to select the div with only the class & ...

Adjusting value of one input field according to the content of another text field in an

Just starting out with Angular and I am looking to dynamically change the value of a hidden input field called 'cc_card' based on the first digit entered in another input field called 'cc_number'. For example, if the user enters 5 in &a ...

What is the best way to resize SVG graphics effectively?

I am in need of creating a seating chart. I have generated an SVG with the seats. <div class="seats-map"> <svg xmlns="https://www.w3.org/2000/svg" id="seats-map-svg" viewBox="0 0 1000 300"> <g data-row ...

Steps for including a font ttf file in Next.js

As a newcomer to Nextjs, I am eager to incorporate my own custom fonts into my project. However, I find myself completely bewildered on how to execute this task (my fonts can be found in the "public/fonts/" directory). The contents of my global.css file ar ...

State loss occurs when moving to a different page using next/link

Currently, I am working on a library application with Next.js. Within this project, there are two main pages: BooksPage, which displays a list of all books, and BookPage, where detailed information about a specific book is shown. The components involved in ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Tips for increasing the font size using html and css?

I am encountering an issue with my HTML code: <div class="a"><font size="40"><font color="black">A</font></font></div> No matter what I try, I cannot seem to increase the font-size. Even adjusting the value in the co ...

Having trouble with a JavaScript element not responding to clicks when displayed inline?

Currently, I am utilizing the "Hotel Datepicker" script found at this website: My goal is to have the datepicker always displayed inline, rather than closing after selecting dates. I attempted to add a function that triggers whenever the datepicker close ...

React's Material-UI AppBar is failing to register click events

I'm experimenting with React, incorporating the AppBar and Drawer components from v0 Material-UI as functional components. I've defined the handleDrawerClick function within the class and passed it as a prop to be used as a click event in the fun ...

Swapping mouse cursor using JavaScript

Currently, I am working on a painting application in JavaScript that utilizes the Canvas Object. I would like to customize the mouse cursor when it hovers over the Canvas object. Can anyone advise me on how to accomplish this? ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

What is the best way to exclude the "table" property from a button inside a row of a table?

I'm currently working with bootstrap and have implemented a table with the property "table" to create a light background for the data pulled from a database. The design looks great, except for when I try to insert a button in each row for editing purp ...