简体   繁体   中英

JavaScript Song play and pausing

I have managed to play and pause an mp3 file as soon as i click an image, the problem is that every time I select another image(which is meant to play a different mp3 song) it automatically resumes the same song.

My JavaScript:

function StartOrStop(audioFile)
  {
    var audie = document.getElementById("myAudio");
    if(!audie.src)
       audie.src = audioFile;
    if(audie.paused == false)
     {
        audie.pause();
     }
     else
     {
       audie.play();
     }
  }

And HTML:

<img src="images/play.png" alt="Play Button" width="57" height="50" onclick="StartOrStop('RWY.mp3')">

<img src="images/play.png" alt="Play Button width="57" height="50" onclick="StartOrStop('EL.mp3')">

<audio controls id="myAudio" ></audio>

Any suggestion how can I solve this problem?

You're not assigning a new src on click, you're checking to see if it exists first. The second file will never be assigned to src since src already exists.

EDIT

You should instead check to see if audie.src === audioFile .

How about this kind of method

<audio id="demo1" src="RWY.mp3"></audio>
<div>
  <button onclick="document.getElementById('demo1').play()">Play the Audio</button>
  <button onclick="document.getElementById('demo1').pause()">Pause the Audio</button>
  <button onclick="document.getElementById('demo1').volume+=0.1">Increase Volume</button>
  <button onclick="document.getElementById('demo1').volume-=0.1">Decrease Volume</button>
</div> 
<audio id="demo2" src="EL.mp3"></audio>
<div>
  <button onclick="document.getElementById('demo2').play()">Play the Audio</button>
  <button onclick="document.getElementById('demo2').pause()">Pause the Audio</button>
  <button onclick="document.getElementById('demo2').volume+=0.1">Increase Volume</button>
  <button onclick="document.getElementById('demo2').volume-=0.1">Decrease Volume</button>
</div> 

Instead of button you can use image just the tag change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM