动态HTML音频播放器

时间:2013-12-26 21:41:44

标签: javascript php html audio

我有从数据库中提取的音频链接。我希望每首歌都有一个播放和暂停按钮,以及一个显示正在播放的歌曲的进度条。目前播放按钮只播放列表中的最后一首歌而不是每首歌曲,我不知道为什么。

<?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>

1 个答案:

答案 0 :(得分:1)

尝试动态生成按钮并将值传递给onclick函数:

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

然后在你的函数中:

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