Search code examples
jqueryhtmlhtml5-audioplayback

Disable all sounds while sound is playing in HTML5/jQuery


I currently have buttons setup to play sounds on an activity. The main audio button plays a sentence. What I'm after is a way to have the other anchors not clickable while the main sentence plays. Here is my HTML firstly:

<audio id="sentence" src="../audio/m_sentence2.mp3"></audio>
<audio id="sound1" src="../../../globalResources/audio/male/hand.mp3"></audio>
<audio id="sound2" src="../../../globalResources/audio/male/foot.mp3"></audio>
<audio id="sound3" src="../../../globalResources/audio/male/nose.mp3"></audio>

<a href="#" class="audioBtn" id="audioMain"></a>
<a href="#" class="audioBtn" id="audio1"></a>
<a href="#" class="audioBtn" id="audio2"></a>
<a href="#" class="audioBtn" id="audio3"></a>

Now I have this jQuery written to play the sounds:

var sentence = $('#sentence');
var sound1 = $('#sound1');
var sound2 = $('#sound2');
var sound3 = $('#sound3');

    $("#audioMain").click(function() {
        sentence.get(0).play();
        });


    $("#audio1").click(function() {
        sound1.get(0).play();       
        });


    $("#audio2").click(function() {
        sound2.get(0).play();       
        });


    $("#audio3").click(function() {
        sound3.get(0).play();       
        });

Is there a way so when the sentence is playing, the other sounds can not be played? I've tried things like removeAttr but can't seem to disable the sounds. I can hide the button completely but that is not an option in this case.


Solution

  • Ok so I've come up with a solution. On the sentence click function, I change the other audio button's pointer-events to none. Then wrote a bind 'ended' event function to the sentence that is playing so when it has finished playing, the other buttons become clickable again. Code below:

    $('#sentence').bind('ended', function() {
            $('#audio1').css('pointer-events', 'auto');
            $('#audio2').css('pointer-events', 'auto');
            $('#audio3').css('pointer-events', 'auto');
    
            }); 
    
    
        $("#audioMain").click(function() {
            sentence.get(0).play();
            $('#audio1').css('pointer-events', 'none');
            $('#audio2').css('pointer-events', 'none');
            $('#audio3').css('pointer-events', 'none');
            });