1 /* Simple example of using SoX libraries
2  *
3  * Copyright (c) 2009 robs@users.sourceforge.net
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
13  * Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #ifdef NDEBUG /* N.B. assert used with active statements so enable always. */
21 #undef NDEBUG /* Must undef above assert.h or other that might include it. */
22 #endif
23 
24 #include "sox.h"
25 #include "util.h"
26 #include <stdio.h>
27 #include <assert.h>
28 
29 /* Example of reading and writing audio files stored in memory buffers
30  * rather than actual files.
31  *
32  * Usage: example5 input output
33  */
34 
35 /* Uncomment following line for fixed instead of malloc'd buffer: */
36 /*#define FIXED_BUFFER */
37 
38 #if defined FIXED_BUFFER
39 #define buffer_size 123456
40 static char buffer[buffer_size];
41 #endif
42 
main(int argc,char * argv[])43 int main(int argc, char * argv[])
44 {
45   static sox_format_t * in, * out; /* input and output files */
46   #define MAX_SAMPLES (size_t)2048
47   sox_sample_t samples[MAX_SAMPLES]; /* Temporary store whilst copying. */
48 #if !defined FIXED_BUFFER
49   char * buffer;
50   size_t buffer_size;
51 #endif
52   size_t number_read;
53 
54   assert(argc == 3);
55 
56   /* All libSoX applications must start by initialising the SoX library */
57   assert(sox_init() == SOX_SUCCESS);
58 
59   /* Open the input file (with default parameters) */
60   assert((in = sox_open_read(argv[1], NULL, NULL, NULL)));
61 #if defined FIXED_BUFFER
62   assert((out = sox_open_mem_write(buffer, buffer_size, &in->signal, NULL, "sox", NULL)));
63 #else
64   assert((out = sox_open_memstream_write(&buffer, &buffer_size, &in->signal, NULL, "sox", NULL)));
65 #endif
66   while ((number_read = sox_read(in, samples, MAX_SAMPLES)))
67     assert(sox_write(out, samples, number_read) == number_read);
68   sox_close(out);
69   sox_close(in);
70 
71   assert((in = sox_open_mem_read(buffer, buffer_size, NULL, NULL, NULL)));
72   assert((out = sox_open_write(argv[2], &in->signal, NULL, NULL, NULL, NULL)));
73   while ((number_read = sox_read(in, samples, MAX_SAMPLES)))
74     assert(sox_write(out, samples, number_read) == number_read);
75   sox_close(out);
76   sox_close(in);
77 #if !defined FIXED_BUFFER
78   free(buffer);
79 #endif
80 
81   sox_quit();
82   return 0;
83 }
84