Search code examples
javascriptphparrayshtml5-audio

Problem when using echo'd ++$value in javascript as part of a html5 audio player page


I have been making myself a 'soundboard' that populates a custom HTML5 audio player for each mp3 file it finds in a directory. Now that side of it is all working exactly as I expected but my problems started when I have attempted to add a custom timer which uses javascript.

For each player, I was able to make custom controls and make the variables all marry up with things like

<audio id="player<?php echo $count1++;?>" src="audio/<?php echo rtrim($file, " "); ?>"></audio>

So using PHP echo a lot to repeat the players and controls but with new ids and as mentioned this is all functioning great but when I try and apply the same to a javascript snippet I'm using this is where my problems start as the ++ seems to be going a bit Pete Tong and is resulting in 2,4,6,8 or 3,6,9,12 when I was expecting 1,2,3,4

Here is the js code in question

// Get the audio element with id from variable
var count10 = "<?php echo $count10 ;?>";
var aud = document.getElementById("player" + count10);

    // Assign an ontimeupdate event to the audio element, and execute a function if the current playback position has changed
    aud.ontimeupdate = function() {myFunction()};

    var count11 = "<?php echo $count11 ;?>";
    function myFunction() {
      // Display the current position of the audio in a p element with id from var
      document.getElementById("time" + count11).innerHTML = aud.currentTime;
    }

To be clear my issue is adding a timer which should appear under each play/stop button once you hit play, this currently only works for the 1st player instance in my pastebin code above.

I've spent 4-5 hours now on nothing but trying to solve this without having to ask on here and have got to the point Its no longer fun! Please help, many thanks.


Solution

  • Rather than keep a separate count to link the the item, you can use the foreach loop to give you the item index...

    So when you do

    foreach ($files as $file) {
    

    you can use

    foreach ($files as $id => $file) { 
    

    and then use

    echo $id;
    

    inside the loop to output the corresponding ID.