1

foreach fetch songs from database each audio have button to pause and play all buttons of all songs works with first song only... when i press button of second or third song the first run ... any solution ?

blade.php

    @foreach($songs as $song)
    <audio  class="player" id="player"  src="{{asset('audios/'.$song->song)}}" type="audio/ogg" > 
   </audio>
        <div class="player-control">
            <button id="{{$song->id}}" class="playerbutton play btn btn-outline-info" 
    onclick="playmusic(this)" ><i class="fas fa-play"></i></button>
    <button id="pause" class="playerbutton pause btn btn-outline-info" 
    onclick="pausemusic(this)"><i class="fas fa-pause"></i></button>
        </div>
        @endforeach

js.file

var player=document.getElementById("player");
  function playmusic()
  {
    
    player.play();

  }
  function pausemusic(elem)
  {
    player.pause();
    
  }

1 Answer 1

1

With var player=document.getElementById("player"); you select only one audio element. If you add a unique song id to the buttons and audio tag like this:

@foreach($songs as $song)
<audio  class="player" id="player-{{$song->id}}" ... </audio>
<div class="player-control">
    <button data-song-id="{{$song->id}}" ... onclick="playmusic(this)" >...</button>
    <button data-song-id="{{$song->id}}" ... onclick="pausemusic(this)">...</button>
</div>
@endforeach

Then you may select a bound audio element directly inside the function:

  function playmusic(e)
  {
    var songId = e.dataset.songId,
     player = document.getElementById("player-" + songId);
     player.play();
  }
  function pausemusic(e)
  {
    var songId = e.dataset.songId,
     player = document.getElementById("player-" + songId);
    player.pause();
  }
Sign up to request clarification or add additional context in comments.

4 Comments

i got an error (Cannot read property 'dataset' of undefined)
Oouch. Please change as follows for each function: onclick="playmusic()" => onclick="playmusic(this)" and e.target.dataset.songId => e.dataset.songId
but what is this (data-song-id)?
It's a data attribute that stores a unique song-id value. Using this value you may select a correct audio player associated with this song by id document.getElementById("player-" + songId) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.