0

When a user clicks on a buttone it plays audio, but when they click on another button that audio stops and it then plays audio for that button and so forth. at the moment when the page loads i also have background music which autoplays, I am trying to figure out how to stop the music playing when a new button is pressed and then that music plays as currently they overlap. Any help would be greatly appreciated.

on load background music code:

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

button clicked audio plays code:

<script>
    $(document).ready(function() {
        var audioElement = document.createElement('audio');
        audioElement.setAttribute('src', 'audio/Dr-No.mp3');
        audioElement.setAttribute('play', 'play');
        //audioElement.load()

        $.get();

        audioElement.addEventListener("load", function() {
            audioElement.play();
        }, true);

        $('#blockLink1').click(function() {
            audioElement.play();
        });
    });
</script>  

1 Answers1

0

Why are you creating elements using pure js when you have jQuery?

<script>
    $(document).ready(function() {
        var audioElement = $('<audio></audio>');

        audioElement.attr('src', 'audio/Dr-No.mp3');
        audioElement.attr('play', 'play');
        //audioElement.load()

        $.get(); // ?

        audioElement.on("load", function() {
            audioElement.get(0).play();
        }, true);

        $('#blockLink1').click(function() {
            $('audio').each(function() {
                this.stop();
            });
            audioElement.get(0).play();
        });
    });
</script>  
Alex
  • 9,911
  • 5
  • 33
  • 52
  • I am quite new to jQuery and development as a whole so my coding will not be that great. Thanks for answering. Is there anything that is supposed to go into the audio tags, as i tried the code but the audio did not play – user3332526 Feb 21 '14 at 12:36
  • since html5 video and audio tags can have s as children – Alex Feb 21 '14 at 13:39