Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play sound through HTML buttons

My current method of playing music through my website is by the HTML audio tags. However I want to be able to play it through HTML button instead. This button should be able to toggle the music between playing and stopping. I've created an example on JSFiddle but don't know how to implement it. Could someone please show me how to do it using my JSFiddle example?

JSFiddle: http://jsfiddle.net/jTh3v/332/

Original way I done it:

document.getElementById("soundTag").innerHTML = "<audio controls volume preload='none' src='http://www.sousound.com/music/healing/healing_01.mp3'></audio>";
like image 246
Garrett Avatar asked Sep 19 '25 01:09

Garrett


2 Answers

you can play sound by onclick event...insert a button on html.write a function and call it at your button as onclick event.

function playMusic(){
  var music = new Audio('musicfile.mp3');
  music.play();
  }
<input type="button" value="sound" onclick="playMusic()" />

Make sure to give a valid filename.

like image 141
Surya Teja Avatar answered Sep 21 '25 13:09

Surya Teja


This worked. Delete my mp3 file and upload your own mp3 file.

<button id="ASong" onClick="playPause()">
  <audio
    src="file_example_MP3_700KB.mp3"
    autoplay
    loop
  ></audio>
  Song
</button>

<script>
  var aud = document.getElementById("ASong").children[0];
  var isPlaying = false;
  aud.pause();

  function playPause() {
    if (isPlaying) {
      aud.pause();
    } else {
      aud.play();
    }
    isPlaying = !isPlaying;
  }
</script>
like image 36
Vanidia Fortes Avatar answered Sep 21 '25 14:09

Vanidia Fortes