0

$(document).ready(function() {

    var audioElement = document.createElement('audio');

    $('#play').click(function() {

        audioElement.play();

    });

});
<script src="http://example.com/wp-content/playsounds.js"></script>
     <button id="play" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
  Button
</button>

I had a question about multiple sources for an audio element.

I read a good way to make buttons playable with javascript at Play an audio file using jQuery when a button is clicked

The problem is I need multiple different sources / play buttons on the same page, for many different pages.

One solution seems to have a separate .js file for each page or even each button, but I know there has to be a simple solution via html or css.

Basically, on my page I want to be able to have buttons with various different sounds, and just put a simple src or source tag and the address of the sound file for each.

I am also using Material Design lite for my buttons.

My current code on my site looks like this

1 Answers1

1

In the example you are referring to, audio element is created dynamically, is there any specific reason you want to do that? In general, you can have as many audio elements as you wish in a page:

<audio id="audio1" src="http://www.soundjay.com/misc/sounds/bell-ringing-05.mp3"></audio>
<audio id="audio2" src="http://www.soundjay.com/misc/sounds/bell-ringing-03.mp3"></audio>
<audio id="audio3" src="http://www.soundjay.com/misc/sounds/bell-ringing-04.mp3"></audio>


<button data-id="audio1" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
  Play audio 1
</button>

<button data-id="audio2" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
  Play audio 2
</button>

<button data-id="audio3" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
  Play audio 3
</button>

One way is to "bind" each audio element with a button, by giving the latter an attribute of data-id that has the same value with the audio id. Then with jQuery (although I would encourage you to use plain JS):

  $('button').on('click', function(){
    var audioId = $(this).data('id');
    $('#' + audioId).get(0).play();
  })

But really, it depends on what you are trying to do. Pen here

Kostas Siabanis
  • 2,989
  • 2
  • 20
  • 22