41e1bd38c2e4 — pouya@nohup.io tip 4 months ago
initial commit
2 files changed, 118 insertions(+), 0 deletions(-)

A => Makefile
A => main.c
A => Makefile +23 -0
@@ 0,0 1,23 @@ 
+CC=pcc
+LD=pcc
+
+CCFLAGS=-O
+LDFLAGS=-static
+
+TARG=beep
+OFILES=main.o
+
+all: ${TARG}
+
+clean:
+	rm -f *.o ${TARG}
+
+.SUFFIXES: .c .o
+
+.c.o:
+	${CC} ${CCFLAGS} -c ${.IMPSRC} -o ${.TARGET}
+
+${TARG}: ${OFILES}
+	${LD} ${LDFLAGS} ${.ALLSRC} -o ${.TARGET} -lm
+
+.PHONY: all clean

          
A => main.c +95 -0
@@ 0,0 1,95 @@ 
+#include <fcntl.h>
+#include <math.h>
+#include <stdint.h>
+#include <sys/audioio.h>
+#include <sys/ioctl.h>
+
+#define PREC    8
+#define ENC     AUDIO_ENCODING_PCM8
+
+#define DEFAULT_RATE	8000
+#define DEFAULT_FREQ	1000
+#define DEFAULT_MSEC	1000
+
+typedef struct Ctx Ctx;
+struct Ctx {
+	int rate, freq, msec;
+} ctx;
+
+int beep(int rate, int freq, int msec);
+int init(int argc, char **argv);
+
+int
+beep(int rate, int freq, int msec) {
+	audio_info_t aufmt = {0};
+	uint8_t s;
+	double step;
+	int fd, e, max;
+	long i, n;
+
+	// init
+	if((fd = open("/dev/audioctl", O_WRONLY)) < 0) return fd;
+	if((e = ioctl(fd, AUDIO_GETINFO, &aufmt)) < 0) return e;
+	aufmt.mode = AUMODE_PLAY;
+	aufmt.play.encoding = ENC;
+	aufmt.play.precision = PREC;
+	aufmt.play.channels = 1;
+	aufmt.play.sample_rate = rate;
+	if((e = ioctl(fd, AUDIO_SETINFO, &aufmt)) < 0) return e;
+
+	close(fd);
+
+	// play
+	if((fd = open("/dev/sound", O_WRONLY)) < 0) return fd;
+
+	n = msec * rate / 1000;
+	max = 1<<PREC-1;
+	step = 2*M_PI*(double)freq/(double)rate;
+	for(i=0; i<n; i++) {
+		s = (double)max * 0.5 * (sin((double)i*step)+1);
+		write(fd, &s, 1);
+	}
+
+	close(fd);
+	return 0;
+}
+
+int
+init(int argc, char **argv) {
+	ctx.rate = DEFAULT_RATE;
+	ctx.freq = DEFAULT_FREQ;
+	ctx.msec = DEFAULT_MSEC;
+	while(--argc) {
+		if(strlen(*++argv) < 2 || **argv != '-') goto usage;
+		switch((*argv)[1]) {
+		case 'h': /* help */
+			goto usage;
+		case 'r': /* rate */
+			if(!--argc) goto usage;
+			ctx.rate = atol(*++argv);
+			break;
+		case 'f': /* freq */
+			if(!--argc) goto usage;
+			ctx.freq = atol(*++argv);
+			break;
+		case 'd': /* duration */
+			if(!--argc) goto usage;
+			ctx.msec = atol(*++argv);
+			break;
+		default:
+			goto usage;
+		}
+	}
+
+	return 0;
+usage:
+	printf("usage: beep [-r rate] [-f freq] [-d msec ]\n");
+	exit(1);
+}
+
+int
+main(int argc, char **argv) {
+	init(argc, argv);
+	beep(ctx.rate, ctx.freq, ctx.msec);
+	return 0;
+}