1

I'm currently working on a code to play HTML5 audio file(s).

Let start with the code first so it would be easier to explain.

Here is my code :

<style>
.btn
{
    background:#fff;
    border-radius:5px;
    border:1px solid #000;
    height:25px;
    width:25px
}

.play:after
{
    content:">"
}

.pause:after
{
    content:"||"
}
</style>

<button class="btn play" id=HeziGangina-Gravity></button>
<button class="btn play" id=HeziGangina-PUG></button>

<script>


iBtn=document.getElementsByTagName('button');

for(j=0;j<iBtn.length;j++)
{
    iBtn[j].addEventListener
    (
        'click',
        function()
        {
            var audio=new Audio(this.id+'.mp3');

            if(audio.pause)
            {
                audio.play();       
                iBtn[j].classList.remove("play");
                iBtn[j].classList.add("pause");
            }
            else
            {
                audio.pause();
                iBtn[j].classList.remove("pause");
                iBtn[j].classList.add("play");
            }

        },false
    );
}

</script>

My current script is working just fine to play the selected audio file but I still have 2 issues to be solved.

  1. I want to be able to change the class name on the current pressed button from play to pause and Vice Versa.

  2. I want to be able to completely disable all other audio file(s) (only) when other track is selected.

[optional]::Is it possible to create ogg audio file fallback with pure javascript (as the same as stacking <source> tags with html)?

Hezi-Gangina
  • 637
  • 6
  • 20

1 Answers1

0
  1. Change your audio.pause to audio.paused
  2. Before play the new track pause all tracks

    if(audio.paused) {
      var audios = document.getElementsByTagName('audio');
    
      for (i = 0; i < audios.length; i++) {
        audios[i].pause();
      }
    
      audio.play();       
      iBtn[j].classList.remove("play");
      iBtn[j].classList.add("pause");
    } else {
      audio.pause();
      iBtn[j].classList.remove("pause");
      iBtn[j].classList.add("play");
    }
    

Hope it will help you.

As for your optional question, you can check the browser using this thread. And make an if statement when you create the Audio to check the browser. So if it's IE or Safari, load mp3, else, load ogg.

Community
  • 1
  • 1
Zakhar Day
  • 401
  • 2
  • 3