单击图像时Javascript暂停声音

时间:2018-01-27 16:44:39

标签: javascript html button playback

我使用播放声音的代码加载图像(我将其用作音乐播放器上的播放按钮)。但是我遇到了问题,单击图像时无法停止声音(播放按钮)。那么,你知道如何对这段代码进行处理,所以在点击图像时会发出声音暂停。

我的代码:

 <script type="text/javascript">
  //Create new function that will update the image source on click.
  function updateImage(el, soundfile) {
      //Determine if music is playing or paused then adjust image 
  source accordingly.
      if(soundfile.mp3.paused) {
          el.src = 

      "imageurl.com";
      } else {
          el.src = "secondimageurl.com";
      }
  };

  function playSound(el,soundfile) {
      if (el.mp3) {
          if(el.mp3.paused) el.mp3.play();
          else el.mp3.pause();
      } else {
          el.mp3 = new Audio(soundfile);
          el.mp3.play();
      }
      //Call new function made whenever the sound is toggled.
      updateImage(document.getElementById("Bottom-1"), el);
  };
   </script>
 <body onload="playSound(this, 'soundsource.mp3');">

 <img src="buttonimage.html" name="Bottom-1" width="50" height="45" 
 border="0" id="Bottom-1"/>
</span>
</body>

1 个答案:

答案 0 :(得分:0)

使用SoundPlayer.js

// Initialize
const player = new SoundPlayer();

// Load the sound
const sound = player.load('Sound.mp3');

// Play the sound
sound.play();

// load & play in one line
const sound = player.load('Sound.mp3').play();

并绑定图像onclick事件

image.onclick = function () {

    sound[ sound.isPlaying ? 'pause' : 'play' ]();
    image.src = sound.isPlaying ? 'isPlaying.jpg' : 'isPaused.jpg';

}

完全小提琴:https://jsfiddle.net/GustavGenberg/dxgph924/