forked from ghewgill/nwr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
play.cpp
74 lines (72 loc) · 1.75 KB
/
play.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
int main(int argc, char *argv[])
{
FILE *f;
if (strcmp(argv[1], "-") == 0) {
f = stdin;
} else {
f = fopen(argv[1], "rb");
if (f == NULL) {
perror("fopen");
exit(1);
}
}
int fd = open("/dev/dsp", O_WRONLY);
if (fd < 0) {
perror("open");
exit(1);
}
int sndparam = AFMT_S16_LE;
if (ioctl(fd, SNDCTL_DSP_SETFMT, &sndparam) == -1) {
perror("ioctl: SNDCTL_DSP_SETFMT");
exit(1);
}
if (sndparam != AFMT_S16_LE) {
perror("ioctl: SNDCTL_DSP_SETFMT");
exit(1);
}
sndparam = 0;
if (ioctl(fd, SNDCTL_DSP_STEREO, &sndparam) == -1) {
perror("ioctl: SNDCTL_DSP_STEREO");
exit(1);
}
if (sndparam != 0) {
fprintf(stderr, "gen: Error, cannot set the channel number to 0\n");
exit(1);
}
int sample_rate = 11025;
sndparam = sample_rate;
if (ioctl(fd, SNDCTL_DSP_SPEED, &sndparam) == -1) {
perror("ioctl: SNDCTL_DSP_SPEED");
exit(1);
}
if ((10*abs(sndparam-sample_rate)) > sample_rate) {
perror("ioctl: SNDCTL_DSP_SPEED");
exit(1);
}
if (sndparam != sample_rate) {
fprintf(stderr, "Warning: Sampling rate is %u, requested %u\n", sndparam, sample_rate);
}
int bytes = 0;
for (;;) {
char buf[4096];
int n = fread(buf, 1, sizeof(buf), f);
if (n == 0) {
break;
}
write(fd, buf, n);
bytes += n;
printf("\r%d", bytes);
fflush(stdout);
}
printf("\n");
close(fd);
fclose(f);
return 0;
}