3

I'm trying to make a little script that will transform my text into morse, I've been able to do that pretty easily, however I'm trying to play the sounds but they are all stack up. I've been trying with addEventListener, but it is only working with the second sound and all the other one are getting "stacked". It is a little bit hard to explain, but how to make a sort of "queue" of sounds that are going to be played one after the other?

At this function, I'm getting the code in morse (eg: **** * *-** *-** ---), and it is reading the morse to make the sounds, but like I said, it is all "stacked".

   function readMorse(){
                  traductionWord(); 
                  var int_position_morse;
                  int_position_morse = 0;
                  while (strCodeMorse.charAt(int_position_morse) != ""){
                      if (strCodeMorse.charAt(int_position_morse) == "*"){
                          playShortSnd();
                          int_position_morse++;    
                      }
                      if (strCodeMorse.charAt(int_position_morse) == "-"){
                          playLongSnd();
                          int_position_morse++;    
                      }
                      if (strCodeMorse.charAt(int_position_morse) == " "){
                          int_position_morse++;
                      }
                  }`  

Sorry if it a bit unclear.

Thanks

prasanth
  • 22,145
  • 4
  • 29
  • 53
  • Playing asound is an asynchronous operation, you have to wait for the sounds to finish. – Tamas Hegedus Nov 16 '16 at 16:50
  • You can try adding a pause after each sound. See this article: http://stackoverflow.com/questions/14226803/javascript-wait-5-seconds-before-executing-next-line – Jacey Nov 16 '16 at 16:52
  • I tried to add a pause, however the pause needed after each "symbols" are differents. In other words, they are not going to be in a good order and some are going to be stacked. – Philippe Jolin Nov 16 '16 at 16:56

1 Answers1

1

A simple solution for your morse player is to queue sounds and play them in order, with pauses.

A very simple implementation could use setInterval:

pendingSounds = []

function queueSound(sound) {
  pendingSounds.push(sound)
}

function playPendingSound() {
  playSound(pendingSounds.shift())
}

setInterval(playPendingSound, 200)

If you want to have pauses of different length, you can use setTimeout each time.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • I've tried your way, but it doesn't seem to work, the sounds are still stacked. The delay seems to only work if I enter many strings, then there's a delay but only between 2 words (not two symbols). – Philippe Jolin Nov 16 '16 at 17:40
  • Have you tried playing with the number of milliseconds? – salezica Nov 16 '16 at 17:53
  • Yeah,by playing with the delay it worked, but it seems that after a certain ammount of symbols, they start to stack up and disynchronize. – Philippe Jolin Nov 16 '16 at 18:20