Play button plays another audio

Asked

Viewed 77 times

3

I call a table posts, and in it is a column post_aud where a text with the audio/music name is 'inserted' (which is 'saved' in the Audios folder)...

$get_posts = "SELECT * FROM posts ORDER by 1 DESC";
$run_posts = mysqli_query($db,$get_posts);
while ($row_posts=mysqli_fetch_array($run_posts)){
$post_aud = $row_posts['post_aud'];

<div name='barra'>
  <i id='play' onclick='play();'></i>
  <i id='pause' onclick='pause();'></i>
<audio id='song' >
   <source src='../audios/$post_aud' type='audio/ogg'>
   <source src='../audios/$post_aud' type='audio/mpeg'>
</audio>

//javascript

function play() {
  document.getElementById('song').play();
}

function pause() {
  document.getElementById('song').pause()
}

//javascript close

</div> //fecha barra
} //fecha while

That is, each post has its own post_aud/music, however, the problem is that every time I press play (in any post) it plays only the audio of the last post inserted (so much so that if I use the normal html player, it works well). Any idea what it might be??? Grateful!!!

  • It wouldn’t be because you’re creating several elements with the same id?

  • pear, same id in table?

  • You cannot repeat the code <audio id='song' >. Cara player must have his own ID. Ex: song1, song2, song3, etc.

1 answer

0


It’s creating several elements with the same id and creating several unnecessary scripts on loop. The correct thing would be to create a count $conta which would be a way to identify each element:

<?php

$get_posts = "SELECT * FROM posts ORDER by 1 DESC";
$run_posts = mysqli_query($db,$get_posts);
$conta = 0;
while ($row_posts=mysqli_fetch_array($run_posts)){
   $post_aud = $row_posts['post_aud'];
?>
<div name='barra<?=$conta?>'>
  <i onclick='play('<?=$conta?>');'></i>
  <i onclick='pause('<?=$conta?>');'></i>

   <audio id='song<?=$conta?>' >
      <source src='../audios/<?=$post_aud?>' type='audio/ogg'>
      <source src='../audios/<?=$post_aud?>' type='audio/mpeg'>
   </audio>
</div>
<?php
   $conta++;
} //fecha while
?>

<script>
function play(id) {
  document.getElementById('song'+id).play();
}

function pause(id) {
  document.getElementById('song'+id).pause()
}
</script>   
  • MY GOD, thank you very much friend, really!!! And wow, I hadn’t even seen the whole script kkk, including this $account (count), you know how it is in English, or the name of this 'function' for me to look for a manual about? Grateful!!!!

  • @Renan Anything friend! This is just a variable that grows in the loop

  • Ahhh $bill = 0 and tals... thank you!! Good night xD

Browser other questions tagged

You are not signed in. Login or sign up in order to post.