下次点击暂停歌曲,Javascript

时间:2017-04-22 22:26:32

标签: javascript

我有5个div盒子在点击时播放某个音轨(使用数据属性),但是,我似乎无法弄清楚如何在下次点击时暂停上一个音轨。音频在彼此之上播放。

Javascript:

var audio = ['song-1.mp3','song-2.mp3','song-3.mp3','song-4.mp3','song-
5.mp3'];

var music = document.querySelector('#container');

music.addEventListener('click', function(evt){
 if(evt.target.tagName === "DIV"){

 var index = evt.target.getAttribute('data-index');

 var sound = new Audio(audio[index]);
 sound.play();

 audio.forEach(function(x){
  if(x !== sound){
   sound.pause();
  }
 })

}

});

HTML:

<!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
    <title></title>
   <link rel="stylesheet" href="style.css"/>
  </head>
 <body>

  <section id="container">
    <div data-index="0"><p>40's</p></div>
    <div data-index="1"><p>50's</p></div>
    <div data-index="2"><p>60's</p></div>
    <div data-index="3"><p>70's</p></div>
    <div data-index="4"><p>80's</p></div>
    <div data-index="5"><p>90's</p></div>
    <div data-index="6"><p>2000's</p></div>
    <div data-index="7"><p>2010's</p></div>
  </section>


 <script src='script.js'></script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

sound将始终引用最近点击的声音,而不是之前播放的声音。最简单的解决方案可能是保留一个跟踪当前正在播放的音频对象的变量playing。这样,当播放新声音时,您可以参考可以暂停的旧声音。这可能看起来像这样

var audio = ['song-1.mp3','song-2.mp3','song-3.mp3','song-4.mp3','song-
5.mp3'];

var music = document.querySelector('#container');

var playing = undefined;

music.addEventListener('click', function(evt){
  if(evt.target.tagName === "DIV"){

    var index = evt.target.getAttribute('data-index');

    var sound = new Audio(audio[index]);
    if (playing) playing.pause();
    sound.play();
    playing = sound;
  }
});

另一个选项是让您保留一组音频对象并跟踪当前播放音频的索引。这看起来像这样。这可能更好,因为它可以保留暂停的歌曲。

var audioNames = ['song-1.mp3','song-2.mp3','song-3.mp3','song-4.mp3','song-
5.mp3'];
var audio = [];
for (var a in audioNames) {
    audio.push(new Audio(a));
}

var music = document.querySelector('#container');

var playingIndex = undefined;

music.addEventListener('click', function(evt){
  if(evt.target.tagName === "DIV"){

    var index = evt.target.getAttribute('data-index');

    var sound = audio[index];
    if (playing) audio[playingIndex].pause();
    sound.play();
    playingIndex = index;
  }
});