1

I want to implement background music on a site i'm creating. Theres also a music video thats pops out when a user hits the play button. How can I pause the background music once the play button is clicked on?

Play button html - The play button triggers a fancybox video popup. This is when I'd like to pause the background sound below.

   <div class="play-btn ">
        <a class="fancybox-media" href="https://vimeo.com/1741943434" >
            <img src="../img/play-btn.svg" alt="">
        </a>
    </div>

Audio file

 <audio autoplay>
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
 Your browser does not support the audio element.
 </audio>

How should I approach this?

Samuel
  • 5,529
  • 5
  • 25
  • 39
  • 1
    An onclick event listener and `.pause()` on the audio element (and maybe a variable to store `isPlaying` in order to play the music back again) should do the job, but you'll have to try coding a bit yourself. – yuriy636 Aug 30 '16 at 11:27

2 Answers2

1

You can use pause() Method,

try with the following code.

<div class="play-btn " onclick="pauseAid()">
    <a class="fancybox-media" href="https://vimeo.com/1741943434" >
        <img src="../img/play-btn.svg" alt="">
    </a>
</div>


 <audio autoplay id="myAudio">
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
 Your browser does not support the audio element.
 </audio>

<script>
var aid = document.getElementById("myAudio"); 
function pauseAid() { 
    aid.pause(); 
}
</script>
Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97
-1
 <audio id="bgmusic" autoplay>
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
 Your browser does not support the audio element.
 </audio>

<script>
 $('.play-btn').on('click', function(){
    $('#bgmusic').get(0).pause(); 
 });
 </script>
Beneris
  • 627
  • 4
  • 11