play button plays another audio

4

I have a table named posts , and there is a post_aud column where a text is inserted with the name of the audio / music (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()
}

// date javascript

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

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

    
asked by anonymous 15.12.2017 / 04:11

1 answer

0

You are creating multiple elements with the same id and creating several unnecessary scripts in loop . The correct one would be to create a count $conta which would be the one 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>   
    
15.12.2017 / 04:41