|
1 /* |
|
2 * $Id: recording.c,v 1.1.1.1 2008-04-28 17:32:53 mbroeker Exp $ |
|
3 * $Source: /development/c/demos/recording.c,v $ |
|
4 * |
|
5 * Program to illustrate /dev/dsp device |
|
6 * Records several seconds of sound, then echoes it back. |
|
7 * Runs until Control-C is pressed. |
|
8 */ |
|
9 |
|
10 #include <unistd.h> |
|
11 #include <fcntl.h> |
|
12 #include <sys/types.h> |
|
13 #include <sys/ioctl.h> |
|
14 #include <stdlib.h> |
|
15 #include <stdio.h> |
|
16 #include <linux/soundcard.h> |
|
17 |
|
18 #define LENGTH 3 /* how many seconds of speech to store */ |
|
19 #define RATE 8000 /* the sampling rate */ |
|
20 #define SIZE 8 /* sample size: 8 or 16 bits */ |
|
21 #define CHANNELS 1 /* 1 = mono 2 = stereo */ |
|
22 |
|
23 /* |
|
24 * this buffer holds the digitized audio |
|
25 */ |
|
26 unsigned char buf[LENGTH * RATE * SIZE * CHANNELS / 8]; |
|
27 |
|
28 int main (int argc, char **argv) |
|
29 { |
|
30 int fd; /* sound device file descriptor */ |
|
31 int arg; /* argument for ioctl calls */ |
|
32 int status; /* return status of system calls */ |
|
33 |
|
34 /* |
|
35 * open sound device |
|
36 */ |
|
37 |
|
38 if (argc != 2) { |
|
39 printf ("Usage: %s <DEVICE>\n", argv[0]); |
|
40 printf ("Example: %s /dev/dsp\n", argv[0]); |
|
41 printf ("Example: %s /dev/dsp1\n", argv[0]); |
|
42 return EXIT_SUCCESS; |
|
43 } |
|
44 |
|
45 fd = open (argv[1], O_RDWR); |
|
46 if (fd < 0) { |
|
47 perror ("open of sound device failed"); |
|
48 return EXIT_FAILURE; |
|
49 } |
|
50 |
|
51 /* |
|
52 * set sampling parameters |
|
53 */ |
|
54 arg = SIZE; /* sample size */ |
|
55 status = ioctl (fd, SOUND_PCM_WRITE_BITS, &arg); |
|
56 if (status == -1) |
|
57 perror ("SOUND_PCM_WRITE_BITS ioctl failed"); |
|
58 if (arg != SIZE) |
|
59 perror ("unable to set sample size"); |
|
60 |
|
61 arg = CHANNELS; /* mono or stereo */ |
|
62 status = ioctl (fd, SOUND_PCM_WRITE_CHANNELS, &arg); |
|
63 if (status == -1) |
|
64 perror ("SOUND_PCM_WRITE_CHANNELS ioctl failed"); |
|
65 if (arg != CHANNELS) |
|
66 perror ("unable to set number of channels"); |
|
67 |
|
68 arg = RATE; /* sampling rate */ |
|
69 status = ioctl (fd, SOUND_PCM_WRITE_RATE, &arg); |
|
70 if (status == -1) |
|
71 perror ("SOUND_PCM_WRITE_WRITE ioctl failed"); |
|
72 |
|
73 while (1) { /* loop until Control-C */ |
|
74 printf ("Say something:\n"); |
|
75 status = read (fd, buf, sizeof (buf)); /* record some sound */ |
|
76 if (status != sizeof (buf)) |
|
77 perror ("read wrong number of bytes"); |
|
78 printf ("You said:\n"); |
|
79 status = write (fd, buf, sizeof (buf)); /* play it back */ |
|
80 if (status != sizeof (buf)) |
|
81 perror ("wrote wrong number of bytes"); |
|
82 /* |
|
83 * wait for playback to complete before recording again |
|
84 */ |
|
85 status = ioctl (fd, SOUND_PCM_SYNC, 0); |
|
86 if (status == -1) |
|
87 perror ("SOUND_PCM_SYNC ioctl failed"); |
|
88 } |
|
89 return EXIT_SUCCESS; |
|
90 } |