Do you want a metronome?

Aug 06, 2009 11:48

Of course you do. I wrote one in C. I originally had ones in Lua and Python, but I decided, "hey, writing it in C would be easy and the resulting executable would be the fastest!", not to mention smallest.

This works on any *NIX system and Cygwin, as far as I know. I use Mac OS 10.5.

mn.c

/*
* Simple command-line metronome.
*/

#include
#include
#include
#include

/*
* A billion ("giga-"): the inverse of a billionth ("nano-"),
* and so the factor value to convert a fractional seconds value
* into nanoseconds.
*/
#define NANO_INVERSE 1000000000 /* 10 ** 9 */
#define SECONDS_IN_MINUTE 60.0

int main(int argc, char **argv)
{
double bpm; /* beats per minute */
double spb; /* seconds per beat */
double int_comp; /* integral component of SPB */
double frac_comp; /* fractional component of SPB */
struct timespec between; /* time between beats */

/* Alternatively, (argc < 2) and ignore all following arguments. */
if (argc != 2)
{
fprintf(stderr, "Usage: %s BPM\n", argv[0]);
return 1;
}

bpm = atof(argv[1]);
spb = SECONDS_IN_MINUTE / bpm;
frac_comp = modf(spb, &int_comp);
between.tv_sec = (time_t) int_comp;
between.tv_nsec = (long) (frac_comp * NANO_INVERSE);

while (1) /* run until interrupted */
{
/* Print a bell character for the sound of the pulse. */
fputc('\a', stdout);
fflush(stdout); /* make sure bells output on time */
nanosleep(&between, NULL);
}

return 0;
}
Makefile

CC=gcc
# CFLAGS=
RM=rm -f
OPT=-fast # change to "-O3" for non-Mac OS X archs
LIBS=-lm
NAME=mn
SRC=$(NAME).c
TARGET=$(NAME)

all: normal fast

normal: $(SRC)
    $(CC) $(CFLAGS) $(LIBS) -o $(TARGET) $^

fast: $(SRC)
    $(CC) $(CFLAGS) $(LIBS) $(OPT) -o $(TARGET)-fast $^

clean:
    $(RM) $(TARGET) $(TARGET)-fast

Note: convert the indenting spaces in the Makefile to tabs or there will be Problems.

Download/view: C source, Makefile.

(Syntax highlighting done with To HTML.)

I haven't posted on LJ in around seven months. Crazy!

c, programming, linux, unix, music, mac

Previous post Next post
Up