Custom control unable to display MP3 file

Hey, I came across this awesome button that I am really interested in using:

https://css-tricks.com/making-pure-css-playpause-button/

I'm currently facing two issues with it. First, I can't seem to play the sound. I've placed the mp3 file in the root directory and I believe I need to add something like

<button class='button'>
  <sound src="play.mp3" type="audio/mpeg">
</button>

Although the standard audio control functions properly, I really want to implement this stylish button. Also, how can I align text to the right of the button?

Furthermore, if I wish to create a list of audio files, what would be the best approach?

Thank you for your assistance 🤟

Answer â„–1

To position text beside a button, you can enclose everything in another div with the CSS properties display: flex; and flex-direction: row;

When it comes to handling audio, I utilize JavaScript to create a new audio object which allows for easy playback control.

If you need to incorporate multiple sounds, simply modify the toggleSound() function to accept a string parameter for the song name. By iterating over the string, you can dynamically check for associated sounds making this method scalable. Add more audio objects along with additional cases in the switch statement and buttons to manage them effortlessly.

In each button, ensure to specify the corresponding audio name so that you can have numerous buttons triggering a single sound.

// example of setting up audio files
const song1 = new Audio(
  "https://ia800905.us.archive.org/19/items/FREE_background_music_dhalius/backsound.mp3"
);

// another sample audio file
const song2 = new Audio(
  "https://ia800905.us.archive.org/19/items/FREE_background_music_dhalius/FormulaFantasy.mp3"
);

function toggleSound(audioName) {
  // switch case to handle different audio files
  switch(audioName.toString()) {
    case "song1":
      var x = song1;
      break;
    case "song2":
      var x = song2;
      break;
    default:
      // set default audio file
      var x = song1;
  }
  
  if (x.paused) {
    x.play();
  } else {
    x.pause();
  }
}
.button {
  margin: 0 10px 10px 0;
  background: lightgray;
}

.button:hover {
  cursor: pointer;
}

.parent {
  display: flex;
  flex-direction: column;
}
<div class="parent">
  <div style="display: flex; flex-direction: row;">
    <!-- your cool button div -->
    <div onclick="toggleSound('song1');" class="button">
      Song 1
    </div>
    Impressive button linked to the first song.
  </div>
  <div style="display: flex; flex-direction: row;">
    <!-- your cool button div -->
    <div onclick="toggleSound('song2');" class="button">
      Song 2
    </div>
    Button for the second song.
  </div>
</div>

Answer â„–2

Here is an example of using HTML:

<button onclick="togglePlay()">Toggle Play</button>
<audio src="music.mp3" id="audioPlayer"></audio>

And JavaScript code for the function:

function togglePlay() {
    var audio = document.getElementById("audioPlayer");
    
    if(audio.paused) {
        audio.play();
    } else {
        audio.pause();
    }
}

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

Fetching a JSON object from an external URL using JavaScript

Currently, I am working on a project using JavaScript and have an API that provides me with a JSON Object. You can access this JSON object by clicking on the following link: . Within this JSON object, there is a specific element located at JSONOBJECT.posi ...

The media query for mobile is not functioning properly

Hello, I have a page with MVC that includes CSS for iPad and mobile devices. The media query for iPad (@media only screen and (min-device-width: 768px) and (max-device-width: 1024px)) works perfectly, but I am struggling to get the media query for mobile ...

Retrieving information from a database by employing AngularJS with the assistance of PHP

I am a beginner in using AngularJS and I am trying to retrieve data from a database using PHP. Here is the code I have tried: <html> <head> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2 ...

step-by-step guide on transferring the text content of an HTML paragraph element to another HTML paragraph element through JavaScript in ASP.NET

I'm looking for help with passing the text value from one HTML paragraph element to another when a JavaScript function is called. The function loads a div element with an enlarged image and a paragraph content. Below is the code I am using: JavaScrip ...

The Angular Material Table experienced a collapse when trying to render over 20 columns simultaneously

Currently, I am experiencing an issue in Angular Version 5 where the Angular Material Table collapses when rendering more than 20 columns. Here is a snapshot of what my table looks like: https://i.stack.imgur.com/MXfvQ.png https://i.stack.imgur.com/XHWgq ...

The process of utilizing variables to form objects in ES6

My ES5 code contains a variable as shown below. var options = { clientId : clientId, keepAlive : keepAlive, clean : clean, reconnectPeriod : reconnectPeriod, will : lastWillMessage }; If I want to convert this to ES6, I can do so by writing ...

Unable to hide content in Shopify using @media

How can I hide a Facebook like button when the browser window is resized to a certain width? This is the code I am using: @media all and (max-width: 300px) { .fb-like { float: right; display: none; } } While this code works on regular websites, it do ...

What is the reason behind the cross-origin error thrown by JSON.parse?

When I don't use JSON.parse, my code works perfectly fine. However, as soon as I attempt to parse or stringify my data object, a cross-origin error is thrown. Why is this occurring and what steps can I take to resolve it? The snippet of code in Title ...

Transforming objects into nested structures

After making a JSON call, I received the following JSON Object: [ { "feeding_id": 14, "supp_name": "Test 1", "supp_weight": 20000, }, { "feeding_id": 14, "supp_name": "Test 2", "supp_weight": 100 ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

Invalid PDF File - Unable to Complete Download via $http

I'm facing an issue while attempting to download a PDF file using the $http service in AngularJS. Upon trying to open the downloaded file, I encounter an error message stating "Invalid Color Space" and the page appears blank. To troubleshoot this pr ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...

Is there an issue with MVC5 in passing JSON data to Controller using Ajax?

I am working on implementing duplication checking in my MVC5/EF Code-First application. In the Asset View's Create() method, I use JavaScript to show/hide textboxes for adding a new location_dept/location_room: <div class="form-group"> ...

Close button located in the upper-right corner is partially cut off

My challenge involves placing a close button on the top right corner of a #main div that contains an image of varying or larger size. I need the close button to slightly protrude outside the div using negative margins. The issue is that when I use overflow ...

Ensuring Navigation Elements Remain Aligned in a Single Line

I'm in the process of developing an interactive project that will be showcased on a touch screen. One of its key features is a fixed footer navigation. Currently, I am using floats to position the main navigation elements and within each element, ther ...

Tips on how to change an image tag into a CSS selector

I need to change this tag to a WebElemet using CSS Selector instead of Xpath. I attempted with Xpath as shown below: panelSectionTitle.find( By.cssSelector( "img.aw-layout-right[style='']" ) ) <img style="" class="aw-layout-right" height="2 ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

What is the best way to create a case-insensitive search feature in Node.js?

I have implemented a search function that takes input from the client as Str. If it matches with content in a file, I send that response. For example, if I have text in a file labeled Lorem, and the client searches for lorem, it returns an empty array due ...

I am currently developing a program that is displaying a blank page despite my efforts to write

I've been trying to write the code below but it only shows a blank page. var greeting = React.createClass({ render: function() { return ( <div> <h1>Hello</h1> </div> ...