Shivam Mitra Shivam Mitra - 1 month ago 4
CSS Question

HTML audio not working inside nested div containers

I am having problem playing audio in html. The audio plays well when I keep the audio tag inside a div container but it doesn't play when I put it inside another div. See the code for better understanding of problem

Case#1:(Works)

<html>
<body>
<div id = "buttons">
<audio src="http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3" id="player"></audio>
<button id = "prev">PREV</button>
<button id = "play" onclick = "play()">PLAY</button>
<button id = "pause" onclick = "pause()">PAUSE</button>
<button id = "next">NEXT</button>
</div>
<script>
function play() {
document.getElementById('player').play();
}
function pause() {
document.getElementById('player').pause();
}
</script>
</body>
</html>


Case#2:(Doesn't works)

<html>
<body>
<div id = "player">
<div id = "buttons">
<audio src="http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3" id="player"></audio>
<button id = "prev">PREV</button>
<button id = "play" onclick = "play()">PLAY</button>
<button id = "pause" onclick = "pause()">PAUSE</button>
<button id = "next">NEXT</button>
</div>
</div>
<script>
function play() {
document.getElementById('player').play();
}
function pause() {
document.getElementById('player').pause();
}
</script>
</body>
</html>

Answer

1st div and audio tag id is same ="player".

So change id of 1st div as I changed it to "playe". If you want your audio tag to have id="player".

Now this will work.

<!doctype html>
<html>

<body>
  <div id="playe">
    <div id="buttons">
      <audio src="test.mp3" id="player"></audio>
      <button id="prev">PREV</button>
      <button id="play" onclick="play()">PLAY</button>
      <button id="pause" onclick="pause()">PAUSE</button>
      <button id="next">NEXT</button>
    </div>
  </div>
  <script>
    function play() {
      document.getElementById('player').play();
    }

    function pause() {
      document.getElementById('player').pause();
    }
  </script>
</body>

</html>

Comments