stinkysGTI
stinkysGTI

Reputation: 611

jquery - Play one audioElement at a time

I'm using mySQL to pull all the existing song data from a table. Everything is working fine, except multiple songs can be played at once. I've tried going about it in various way, but nothing has been working, nor do I get any errors.

It can be viewed here: http://www.sensationshowband.com/videomusicgallery/

and if you view the source, the code I'm working with is at the bottom of the page.

This will look a bit messy, but here's the code that my query loops though before it gets rendered:

echo "var audioElement".$row[0]." = document.createElement('audio');\n";
echo "audioElement".$row[0].".setAttribute('class', 'div-".$row[0]."');\n";
echo "audioElement".$row[0].".setAttribute('src', '".$row[4]."');\n";
echo "$.get();\n";
echo "audioElement".$row[0].".addEventListener('load', function() {\n";
echo "audioElement".$row[0].".play();\n";
echo "}, true);\n";
echo "$('.play".$row[0]."').click(function() {\n";
echo "if (audioElement".$row[0].".paused == false) {\n";
echo "audioElement".$row[0].".pause();\n";
echo "$('.play".$row[0]."').css('background','url(/wp-content/themes/sensation/images/play.png) 0px 8px no-repeat');\n";
echo "} else {\n";
echo "audioElement".$row[0].".play();\n";
echo "$('.play".$row[0]."').css('background','url(/wp-content/themes/sensation/images/pause.png) 0px 8px no-repeat');\n";
echo "}\n";
echo "});\n";

Where it initiates the play function (echo "audioElement".$row[0].".play();\n";), I tried adding this:

$("audio").on("play", function() {
    $("audio").not(audioElement.$row[0]).each(function(index, audio) {
        audio.pause();
    });
});

That didn't work though. Is it because I'm creating an element rather than having an actual audio tag?

Upvotes: 0

Views: 66

Answers (1)

Scelesto
Scelesto

Reputation: 795

Yeah, that's pretty messy. Anyway, here's a solution that should work.

Javascript:

playing=false;
function play(index) {
     eval('audioElement'+index+'.play();');
     $('.play'+index).css('background','url(/wp-content/themes/sensation/images/pause.png) 0px 8px no-repeat');
     playing=index;
}
function pause(index) {
     if(index==false) {
          return;
     }
     eval('audioElement'+index+'.pause();');
     $('.play'+index).css('background','url(/wp-content/themes/sensation/images/play.png) 0px 8px no-repeat');
     playing=false;
}

PHP:

<?php
...
foreach($column as $row) {
?>
var audioElement<?=$row[0]?> = document.createElement('audio');
audioElement<?=$row[0]?>.setAttribute('class', 'div-<?=$row[0]?>');
audioElement<?=$row[0]?>.setAttribute('src', '<?=$row[4]?>');
$.get();
audioElement<?=$row[0]?>.addEventListener('load', function() {
    pause(playing);
    play(<?=$row[0]?>);
}, true);
$('.play<?=$row[0]?>').click(function() {
    if (playing==<?=$row[0]?>) {
        pause(<?=$row[0]?>);
    } else {
        pause(playing);
        play(<?=$row[0]?>);
    }
});
<?php
}
...
?>

Upvotes: 1

Related Questions