简体   繁体   中英

Dynamic HTML audio player

I have audio links that are being pulled in from a database. I want to have a play and pause button for each song and a progress bar that shows whatever song is playing. Currently the play buttons only will play the last song on the list not each individual song and I don't know why.

<?php
include '../../header.php';
session_start();
if(!$_SESSION['logged']){
    header("Location: index.php");
    exit;
}
?>

<!--static labels-->
<div class="container">
<ul class="list-group">
<li class='col-xs-3 list-group-item'>Title</li>
<li class='col-xs-6 list-group-item'>Description</li>
<li class='col-xs-3 list-group-item'><audio id="theplayer" controls></audio></li>
</ul>
</div>
</br>
<!--sql query and dynamic html elements-->
<?php
$tableUser = $_SESSION['username'];
 $con = mysqli_connect("127.0.0.1:3306","localhost","","songstorage"); 
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$result = mysqli_query($con,"SELECT * FROM $tableUser");
while($row = mysqli_fetch_array($result))
  {
      echo "<div class='container'><ul>";
      echo  "<li class='col-xs-1'>".$row['songid']."</li>";
      echo "<li class='col-xs-4'>".$row['title']."</li>";
      echo "<li class='col-xs-7'>".$row['description']."</li>";
      echo "<li class='col-xs-3'><button onclick='playaudio()' type='button'>Play</button><audio id='".$row['songid']."'><source src='".$row['url']."'></audio></li>";
      echo "</ul></div>";
      echo "<script type='text/javascript'>
var myAudio=document.getElementById('".$row['songid']."');
function playaudio(){
    myAudio.load();
    myAudio.play();
}
function pauseaudio()
  { 
  myAudio.pause(); 
  } 
  </script>";
      $audioid = array($row['songid']);
       var_dump($audioid);
       }
?>

<!--buttons and audio elements for testing-->
<audio id="testaudio"><source src="18secFX.wav"></audio>


<!--script to pull play audio links-->
<?php
//  $songids = mysqli_query($con,"SELECT songid FROM $tableUser");
//$songarray = mysqli_fetch_row($songids);
//var_dump($songarray);

?>

<?php
  mysqli_close($con);
?>
<button onclick="playaudio()" type="button">Play Video</button>
<button onclick="pauseaudio()" type="button">Pause Video</button> 


</body>
</html>

Try dynamically generating your buttons and passing a value to the onclick function:

<button onclick="playaudio(".$row['songid'].")" type="button">Play Video</button>

and then in your function:

 function playaudio(songid){
 document.getElementById(songid).load();
 document.getElementById(songid).play();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM