Home > Software engineering >  call function (audio playing) in order
call function (audio playing) in order

Time:08-24

I hava a function that playing audios in order. But there may be a case where the function is called almost at the same time, and all audios playing is mixed. How can I call the same function where audios order of the second call is played after the audios order of the first call.

function playSound() {
  $('#content').append('<audio id="ding" src="ding.wav" preload="auto"></audio>');
  $('#ding')[0].play();
  $('#ding')[0].onended = function() {

    $('#content').append('<audio id="number" src="sound/voice/number.wav" preload="auto"></audio>');
    $('#number')[0].play();
    $('#number')[0].onended = function() {

      $('#content').append('<audio id="goToCounter" src="sound/voice/goToCounter.wav" preload="auto"></audio>');
      $('#goToCounter')[0].play();

    }
  }
}

CodePudding user response:

One possible way is to have a counter that counts the number of times the playSound function is called. If it is still in the middle of playing sounds, increase the counter, but return from the function. Only after the playing of the three sounds is finished, you call playSound again if there are still calls in the queue.

    var numberOfTimesAudioHasStarted = 0;
    function playSound(buttonClicked) {
        if(buttonClicked === true){
            numberOfTimesAudioHasStarted  ;
        }
        if(numberOfTimesAudioHasStarted > 1 && buttonClicked === true){
            return;
        }
        $('#content').append(
                '<audio id="ding" src="https://thumbs.dreamstime.com/audiothumb_22779/227796222.mp3" preload="auto"></audio>');
        $('#ding')[0].play();
        $('#ding')[0].onended = function() {
            $('#content')
                    .append(
                            '<audio id="number" src="https://thumbs.dreamstime.com/audiothumb_22779/227796222.mp3" preload="auto"></audio>');
            $('#number')[0].play();
            $('#number')[0].onended = function() {
                $('#content')
                        .append(
                                '<audio id="goToCounter" src="https://thumbs.dreamstime.com/audiothumb_11413/114136296.mp3" preload="auto"></audio>');
                $('#goToCounter')[0].play();
                $('#goToCounter')[0].onended = function() {
                    numberOfTimesAudioHasStarted--;
                    if(numberOfTimesAudioHasStarted > 0){
                        playSound(false);
                    }
                }
            }
        }
    }
    $('button').click(function() {
        playSound(true);
    });
<div id="content"></div>
<button>play</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Note that this function keeps adding audio elements to the page every time the function runs. This is bad practice, since no two elements with the same id should be present on a page.

  • Related