Version 3.0.2
[rtaudio.git] / tests / record_raw.cpp
1 /******************************************/
2 /*
3   record_raw.c
4   by Gary P. Scavone, 2001
5
6   Records from default input.  Takes
7   number of channels and sample rate
8   as input arguments. Uses blocking calls.
9 */
10 /******************************************/
11
12 #include "RtAudio.h"
13 #include <iostream>
14 #include <stdio.h>
15
16 /*
17 typedef char  MY_TYPE;
18 #define FORMAT RTAUDIO_SINT8
19
20 typedef signed short  MY_TYPE;
21 #define FORMAT RTAUDIO_SINT16
22
23 typedef signed long  MY_TYPE;
24 #define FORMAT RTAUDIO_SINT24
25
26 typedef signed long  MY_TYPE;
27 #define FORMAT RTAUDIO_SINT32
28 */
29
30 typedef float  MY_TYPE;
31 #define FORMAT RTAUDIO_FLOAT32
32
33 /*
34 typedef double  MY_TYPE;
35 #define FORMAT RTAUDIO_FLOAT64
36 */
37
38 #define TIME   2.0
39
40 void usage(void) {
41   /* Error function in case of incorrect command-line
42      argument specifications
43   */
44   std::cout << "\nuseage: record_raw N fs <device>\n";
45   std::cout << "    where N = number of channels,\n";
46   std::cout << "    fs = the sample rate,\n";
47   std::cout << "    and device = the device to use (default = 0).\n\n";
48   exit(0);
49 }
50
51 int main(int argc, char *argv[])
52 {
53   int chans, fs, buffer_size, device = 0;
54   long frames, counter = 0;
55   MY_TYPE *buffer;
56   FILE *fd;
57   RtAudio *audio = 0;
58
59   // minimal command-line checking
60   if (argc != 3 && argc != 4 ) usage();
61
62   chans = (int) atoi(argv[1]);
63   fs = (int) atoi(argv[2]);
64   if ( argc == 4 )
65     device = (int) atoi(argv[3]);
66
67   // Open the realtime output device
68   buffer_size = 512;
69   try {
70     audio = new RtAudio(0, 0, device, chans,
71                         FORMAT, fs, &buffer_size, 8);
72   }
73   catch (RtError &error) {
74     error.printMessage();
75     exit(EXIT_FAILURE);
76   }
77
78   fd = fopen("test.raw","wb");
79   frames = (long) (fs * TIME);
80
81   try {
82     buffer = (MY_TYPE *) audio->getStreamBuffer();
83     audio->startStream();
84   }
85   catch (RtError &error) {
86     error.printMessage();
87     goto cleanup;
88   }
89
90   std::cout << "\nRecording for " << TIME << " seconds ... writing file test.raw (buffer size = " << buffer_size << ")." << std::endl;
91   while (counter < frames) {
92
93     try {
94       audio->tickStream();
95     }
96     catch (RtError &error) {
97       error.printMessage();
98       goto cleanup;
99     }
100
101     fwrite(buffer, sizeof(MY_TYPE), chans * buffer_size, fd);
102     counter += buffer_size;
103   }
104
105   try {
106     audio->stopStream();
107   }
108   catch (RtError &error) {
109     error.printMessage();
110   }
111
112  cleanup:
113   audio->closeStream();
114   delete audio;
115   fclose(fd);
116
117   return 0;
118 }