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

Using Material UI, I have styled a typography element and a button to appear on the

Struggling to position a button and a <Typography> element side by side: Here's what I currently have: <Grid item lg={12} md={12} sm={12} xs={12} className={classes.register}> <Typography noWrap className={classes.typoText} varian ...

Do individual JavaScript script tags operate independently of one another in terms of error handling?

My main goal is to establish a connection to my server using websockets and send messages to the browser for remote page reloads. I want to ensure that this code runs independently of any other errors on the page, allowing me to remotely refresh the page i ...

Expanding properties in a React component based on certain conditions using TypeScript

I am attempting to dynamically expand my component props based on whether a specific prop is included. The goal is to add attributes from an anchor if the href prop is provided, and include attributes from a button if it is not. Is this achievable? Chec ...

The value of the HTML input control vanishes once padding is added

I am in need of some assistance with CSS in formatting the text box for BID VALUE (input element) (See in Image 1) Image 1 The product link can be found here When I try to widen the text box using padding, the text value inside the box disappears (seems ...

Looking to update table content dynamically using jQuery ajax?

I need assistance in creating a dynamic table that can update its content based on the company selected from a dropdown menu. The data should be fetched using AJAX and only display information related to the chosen company. Furthermore, I would like to imp ...

Error: The function .join is not recognized by the sockets.io library in a Node.js client-server environment

I'm currently working on developing a chat app using node and vue js, and I've encountered an issue with the socket.io library. Specifically, I keep receiving an error stating that ".join is not a function" when trying to use it in my server-side ...

What is the best way to create an HTML form on-the-fly from a JSON object?

Could someone please assist me in understanding how to dynamically generate an HTML form based on a JSON object using JavaScript? ...

"Comparison: Utilizing HTML5 Video Player with IE8 Embed Fallback versus Implementing Fixed

This dilemma has me at my wit's end. In an HTML5 Video element, I've included an mp4, ogg, and an embedded mp4 fallback. However, on the embed fallback in IE8, all my attempts to position the fixed element (#fixed) above it with z-indexing have f ...

What is the best way to trigger an API call using AJAX whenever the page loads and at regular intervals using `setInterval()` function?

New to coding and seeking guidance: I have a basic AJAX feature in my project that triggers a GET API request every 3 seconds: <script> $(document).ready( function() { setInterval(function() { $.get(&apos ...

Effective management and structuring of ExpressJS routes

I recently made the switch from PHP to NodeJS and Express, and I must say, it has been quite a learning experience. Following online tutorials to build web apps with Express has been eye-opening. I decided to tackle a project using just JavaScript, but I ...

Ensuring jQuery filter() works seamlessly with Internet Explorer versions 6, 7, and 8

On my webpage, I have implemented an ajax call using the jQuery library to handle a specific task. After making the ajax call, I need to parse the response message that is returned. However, I encountered an issue with Internet Explorer versions 6, 7, and ...

Layered parallax scenery

I'm interested in creating a parallax effect similar to this example. https://medium.com/@PatrykZabielski/how-to-make-multi-layered-parallax-illustration-with-css-javascript-2b56883c3f27 However, I find the use of HAML and Coffeescript in the mentio ...

AngularJS Large file size

After successfully building the 5 MIN QUICKSTART app, I decided to minify it with webpack following the recommendations in the angularJS docs. To my surprise, the size of the minified AngularJS file turned out to be approximately 700 KB, which is significa ...

Looking to replace a background image using javascript?

(apologies for any language mistakes) I have multiple divs with a common background image. I assigned them the same class and set the background image using CSS in style.css which worked perfectly fine. Now, I want to change the background image dynamical ...

Issue with React component not receiving dataThe values are not being

Currently, I am a beginner in using React and as part of my training, I have embarked on a project to create a simple book ranking system. In this project, the user enters the title of the book they would like to vote for. If the input field is left empty, ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

React: Show input value on button click

I have been working on a React form that displays the entered input value in a controlled input element only after the user hits the submit button, rather than updating it constantly as the user types. Here is my current solution using conditional renderin ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

File in Node JS appears to be empty upon reading

My goal is to track the location of tweets in separate JSON files for each Twitter ID I monitor. The code snippet below is executed for every tweet, creating a new JSON file for each unique ID and appending the location data: console.log("@ " + tweet.user. ...