Search code examples
javascripthtmlloopsbuttonmp3

How can I loop a mp3 file with javascript and html


thanks for taking a look, today I decided to add some sound to my website and thats where it goes wrong, the point is to press the button and than the mp3 should loop, I know it works with a wav but it doesn't with a mp3, so here is my question. Can I adapt the script in order to make the mp3 loop?

javascript:

 <script language="javascript" type="text/javascript">
     function playSound(soundfile) {
      var type_attr = '';
      if (navigator.userAgent.indexOf('Firefox') != -1) {
        type_attr = "type=\"application/x-mplayer2\"";
      }
      document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"true\" " + type_attr + " />";
    }
     </script>

Html:

<span id="dummy">
  <tr>
    <td><input type="button" class='gstring' value="G" width="50" height="50" onClick="playSound('violin/Gstring.mp3')"></td>
    <td><input type="button" class='gstring' value="D" width="50" height="50" onClick="playSound('violin/Dstring.mp3')"></td>
    <td><input type="button" class='gstring' value="A" width="50" height="50" onClick="playSound('violin/Astring.mp3')"></td>
    <td><input type="button" class='gstring' value="E" width="50" height="50" onClick="playSound('violin/Estring.mp3')"></td>
    <td><input type="button" class='g2string' value="STOP" width="70" height="50" onClick="playSound('')"></td>
  </tr>
  </span>

The reasen why I don't want to use wav is because it's +/- 1mb for a sound file ( I am g oing to use a lot of them) and I Can't afford a big hosting plan so I would rather use mp3 instead. I hope there is a possibility.

thanks, Diederik.


Solution

  • On this webpage they describe different solutions how to play mp3 sound. I tried HTML5 audio element and it worked even for loops with mp3 which they have there (sometimes it took a while to load the mp3 but after few seconds the sound started in the loop)

    <!DOCTYPE html>
    <html>
    
    <script>
        function play_pause() {
            var myAudio = document.getElementById("myAudio");
            if (myAudio.paused) {
                myAudio.play();
            } else {
                myAudio.pause();
            }
        }
    </script>
    
    <body>
    
        <button type="button" onclick="play_pause()">Play/Pause</button>
    
        <audio id="myAudio" preload loop>
          <source src="horse.mp3" type="audio/mpeg">
          Your browser does not support this audio format.
        </audio>
    
    </body>