Home > OS >  how to add 2 3 songs to website using html javascript
how to add 2 3 songs to website using html javascript

Time:10-04

I am still newbie I'm studying,

help if you can I don't understand, I want to add 2 3 songs to the site I wrote the code but only 1 song works how to make all songs play but not simultaneously, but in turn,

For example I am listening to music 1 and then I want to listen to play 2, when I press play 2, play 1 should stop how to do it i don't understand can you help in advance thanks I'll leave the code

var mySong = document.getElementById("mySong");
var icon = document.getElementById("icon");

icon.onclick = function() {
  if(mySong.paused){
      mySong.play();
      icon.src = "img/pause-icon.png";
  }else{
    mySong.pause();
    icon.src = "img/play-icon.jpg";
  }
}
<img src="img/play-icon.jpg" alt="" id="icon" width="80">

          <audio id="mySong">
            <source src="Ганвест - Кайфули.mp3" type="audio/mp3">
          </audio>

          <img src="img/play-icon.jpg" alt="" id="icon" width="80">

          <audio id="mySong">
            <source src="Ганвест - Кайфули.mp3" type="audio/mp3">
          </audio>

CodePudding user response:

You need unique IDs or delegate, then you do not need IDs at all:

Note I changed icon id to icon class, wrapped each song in a div and all songs in a div too

const icons = {
  play: "https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png",
  pause: "https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/play-pause.png"
}
const isPlaying = audioElement => !audioElement.paused;

const container = document.getElementById("songs");
const songs = container.querySelectorAll(".song audio");
const controls = container.querySelectorAll(".song .icon");

container.addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.matches(".icon")) {
    const mySong = tgt.closest(".song").querySelector("audio");
    // pause all other songs
    songs.forEach((song,i) => {
      if (isPlaying(song) && song != mySong) {
        song.pause()
        controls[i].src=icons.play;
      }
    }); 
    if (mySong.paused) {
      mySong.play();
      tgt.src = icons.pause;
    } else {
      mySong.pause();
      tgt.src = icons.play;
    }
  }
})
<div id="songs">
  <div class="song">
    <img src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png" alt="Toggle" class="icon" width="80">

    <audio id="mySong1">
      <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mp3"></audio>
  </div>
  <div class="song">
    <img src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png" alt="Toggle" class="icon" width="80">

    <audio id="mySong2">
      <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" type="audio/mp3"></audio>
  </div>
</div>

  • Related