beep: implement the same API as the standard 'beep' from Linux

This commit is contained in:
K. Lange 2018-11-29 17:33:31 +09:00
parent 367e3afd94
commit 92a06067a2

View File

@ -1,9 +1,10 @@
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2014 K. Lange
* Copyright (C) 2014-2018 K. Lange
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
@ -14,7 +15,7 @@ struct spkr {
int frequency;
};
void note(int length, int frequency) {
static void note(int length, int frequency) {
struct spkr s = {
.length = length,
.frequency = frequency,
@ -23,6 +24,27 @@ void note(int length, int frequency) {
write(spkr, &s, sizeof(s));
}
/* Stolen from the Linux tool */
#define DEFAULT_FREQ 440.0
#define DEFAULT_LEN 200
#define DEFAULT_DELAY 100
static int repetitions = 1;
static float frequency = DEFAULT_FREQ;
static int length = DEFAULT_LEN;
static int delay = DEFAULT_DELAY;
static int beep_after = 0;
void beep(void) {
for (int i = 0; i < repetitions; ++i) {
note(length, frequency * 10);
if (delay && ((i != repetitions - 1) || beep_after)) {
usleep(delay * 1000);
}
}
}
int main(int argc, char * argv[]) {
spkr = open("/dev/spkr", O_WRONLY);
@ -30,25 +52,38 @@ int main(int argc, char * argv[]) {
fprintf(stderr, "%s: could not open speaker\n", argv[0]);
}
note(20, 15680);
note(10, 11747);
note(10, 12445);
note(20, 13969);
note(10, 12445);
note(10, 11747);
note(20, 10465);
note(10, 10465);
note(10, 12445);
note(20, 15680);
note(10, 13969);
note(10, 12445);
note(30, 11747);
note(10, 12445);
note(20, 13969);
note(20, 15680);
note(20, 12445);
note(20, 10465);
note(20, 10465);
int opt;
while ((opt = getopt(argc, argv, "?r:f:l:d:D:n")) != -1) {
switch (opt) {
case 'r':
repetitions = atoi(optarg);
break;
case 'l':
length = atoi(optarg);
break;
case 'f':
frequency = atof(optarg);
break;
case 'd':
delay = atoi(optarg);
beep_after = 0;
break;
case 'D':
delay = atoi(optarg);
beep_after = 1;
break;
case 'n':
beep();
repetitions = 1;
frequency = DEFAULT_FREQ;
length = DEFAULT_LEN;
delay = DEFAULT_DELAY;
beep_after = 0;
break;
}
}
beep();
return 0;
}