2

Here is a simple metronome script in Bash using ASCII bell.

#!/bin/bash

read -s tempo
interval=$(bc -l <<< "scale=4; 60/$tempo")

echo -n "tempo is $tempo  interval is $interval seconds"

while true
do
        echo -en "\a"
        sleep $interval
done

The bug I'm encountering:

When tempo is set at more than 60, metronome script will start always at 120BPM initially, and only update to the correct tempo fast or slower after I interrupt it by hitting a random key.

I also tried it in Java and encountered the same issue.

import java.util.Scanner;
import java.lang.Runtime;
import java.io.*;

public class Metronome {

  public static void main(String[] args) throws InterruptedException { 

    Scanner in = new Scanner(System.in);

    double tempo = in.nextDouble();
    double interval = (60 / tempo) *1000;


    while (true) {
        System.out.println("\u0007");
        Thread.sleep((long) interval);
    }

  }

}

Is there a system default interval time that is set between bell chimes? How come it changed speed after I interrupt the thread/job?

wileypoots
  • 31
  • 2

1 Answers1

0

I don't think there is an enforced minimal interval between two beeps, but each beep itself has a certain duration, which is smaller than a second, but at least long enough that you hear the beep as a beep and not as a click. If you send two beeps in sequence, and the sending interval is shorter than the beep duration, the \0007 characters are simply queued up in a buffer and processed in sequence. The effect is as if you would send text to the terminal faster than it can be displayed.

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • I am aware of the duration. I was able to get the bell chime to play at 400 BPM or whatever the tempo I set, but only after I press a key to interrupt the initial bell playing, which is always at 120BPM. So it can definitely play fast but it seems there's something wrong with my bash setting or terminal setting... Thanks for the buffer tips though -- I have very limited knowledge on how that works, do you have a link you recommend on buffer in bash by any chance? – wileypoots May 12 '20 at 03:10
  • This has nothing to do with bash. It is just the usual mechanism when any application is writing to stdout, as you could see when doing it in Java. But what would maybe help is to write the output unbuffered, for instance by write to stderr instead (in bash: `echo .... 1>&2`). – user1934428 May 12 '20 at 07:06