3

I'm using the wavesurfer.js to generate a waveforms for audio clips, the problem I am having is that I have multiple audio files being pulled in a php while loop, and the javascript only seems to run for the first record returned..

I'll post what i've tried below, as you can see I have tried to make it unique and run every loop but I have run out of ideas and searched everywhere on the internet but nothing helped.

PHP:

 global $db;
 $select = $db->query("SELECT * FROM audio ORDER BY id DESC");
  while ($row = $select->fetch_assoc()) {
   echo $row["track_title"] . " by " . $row["artist"] . "<br />";
   $path = $row['path'];
   $path = str_replace("..", "", $path);
   $id = $row['id'];

    echo"
     <div class='waveid' id='".$id."'>
     <div class='path' id='".$path."'>
     <div class='cursor' id='wave-cursor'></div><canvas id='wave' class='wave-".$id."' width='1024' height='128'></canvas>
     </div>
     </div> 
    ";
    }

JAVASCRIPT:

var id = $(".waveid").attr('id');
var path = $(".path").attr('id');

console.log(id);
console.log(path);

var wavesurfer = Object.create(WaveSurfer);

wavesurfer.init({
canvas: document.querySelector('.wave-'+id),
waveColor: 'violet',
progressColor: 'purple'
});

wavesurfer.load(path);

To sum up, I have a while loop returning all the song data with the mp3's stored in a folder, the file paths are stored in the database and are being returned. I'm trying to make a unique waveform for each file but for some reason I can only manage to get the one waveform for the first record. Any help would be greatly appreciated.

EDIT: also if anyone wished to edit the title or any content/tags please feel free to do so.

chriz
  • 1,580
  • 19
  • 27
  • 2
    I don't know if this is the problem you're having, but you have many elements with the same `id`. – Brad Mar 18 '13 at 22:13
  • @Brad I think i have made them all different... Thats why this is confusing me. Someone please correct me if i've done it wrong though – chriz Mar 18 '13 at 22:16
  • `#wave-cursor` and `#wave` are duplicated. – Brad Mar 19 '13 at 00:08

1 Answers1

1

PHP (you don't need to use divs):

while ($row = $select->fetch_assoc()) {
 echo $row["track_title"] . " by " . $row["artist"] . "<br />";
 $path = $row['path'];
 $path = str_replace("..", "", $path);
 $id = $row['id'];

 # make sure $path doesn't contain ' character
 echo "<canvas class='wave' data-path='$path' data-id='$id' width='1024' height='128'></canvas>";
}

JS (this will make all waves):

$('.wave').each(function(){
 var wavesurfer = Object.create(WaveSurfer);

 wavesurfer.init({
  canvas: this,
  waveColor: 'violet',
  progressColor: 'purple'
 });

 wavesurfer.load($(this).data('path'));
});