最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript play and pause a song with one click on the same image - Stack Overflow

programmeradmin1浏览0评论

Hi im trying to have a song play when i click and pause when i click it again however it only seems to be playing this is the code below:

Javascript

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

HTML5

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

Any suggestion on how i can fix it ?

Hi im trying to have a song play when i click and pause when i click it again however it only seems to be playing this is the code below:

Javascript

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

HTML5

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

Any suggestion on how i can fix it ?

Share Improve this question edited Mar 23, 2013 at 20:03 user2202031 asked Mar 23, 2013 at 12:33 user2202031user2202031 251 gold badge1 silver badge7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

When ever you click the image, it calls the StartOrStop function, this will cause the src of video set again thus cause paused to be true so you can't pause the video but just play it again.

This version should work:

HTML:

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

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

Javascript:

function StartOrStop(audioFile) {
    var audie = document.getElementById("myAudio");
    if (!audie.src || audie.src !== audioFile) audie.src = audioFile; // check if there's a src already and if the current src is not the same with the new one, change it. Or don't do anything.
    if (audie.paused == false)
        audie.pause();
    else
        audie.play();
}

Fiddle: http://jsfiddle/QCGYP/4/

发布评论

评论列表(0)

  1. 暂无评论