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