[PPA 06] Archivos de audio y normalización de señales.

Aquí va un programa que puede leer y escribir archivos de audio en
varios formatos usando la librería sndfile. Además muestra como usar getopt_long para análizar los
parámetros de línea de comando del programa y muestra un algorimo básico
para normalizar señales.

Instalación de Pre-requisitos:

En Mac Os X: brew install flac libogg libvorbis libsndfile

En Linux: sudo apt-get install libflac-dev libogg-dev libvorbis-dev libsndfile-dev

makefile:

1
2
3
4
5
6
7
8
9
10
11
12
COMPILER = g++
LINKER = g++
COMPILER_FLAGS = -Wall -g -c
LINKER_FLAGS = -lsndfile

normalize: normalize.cpp
  $(COMPILER) $(COMPILER_FLAGS) normalize.cpp -o normalize.o
  $(LINKER) $(LINKER_FLAGS) normalize.o -o normalize

.PHONY: clean
  -rm normalize.o
  -rm normalize

normalize.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
#include <getopt.h>
#include <sndfile.h>
#include <cmath>

#define VERSION 0.1
// #define DEBUG 1

#define BUFFER_LENGTH 512

// Global Variables
std::string format = ""; // format of output file
int majorFormat = 0; // see sndfile.h
int minorFormat = 0;
unsigned int sampleRate = 0; // SR for output file
std::string inFilePath = "";
std::string outFilePath = "";
int numChannels = 0;

//========================================================//
//  Analize program parameters and set global variables.  //
//========================================================//
void parseParameters(int argc, char *argv[]) {

  // Help message
  std::string help = "Usage: normalize [-flags] -i <infile> -o <outfile>\n\n";
  help += "Flags:\n";
  help += "-f <output format>       -- specify one of wav, aiff, au or flac. default is same as input file\n";
  help += "-sr <output sample rate> -- default is same as input file\n";
  help += "-version                 -- print version of the normalize program\n";
  help += "-help                    -- print this message\n\n";

  // Get the flag values and store.
  int showVersion = 0;
  int showHelp = 0;
  const struct option long_options[] = {
    {"i", required_argument, NULL, 'i'},
    {"o", required_argument, NULL, 'o'},
    {"f", required_argument, NULL, 'f'},
    {"sr", required_argument, NULL, 's'},
    {"version", no_argument, &showVersion, 1},
    {"help", no_argument, &showHelp, 1},
    { NULL, no_argument, NULL, 0 }
  };
  int option_index;
  int c;
  while((c = getopt_long_only(argc, argv, "i:o:f:s:", long_options, &option_index)) != -1){
    switch (c){
      case 'i':
        inFilePath = std::string(optarg);
        break;
      case 'o':
        outFilePath = std::string(optarg);
        break;
      case 'f':
        format = std::string(optarg);
        break;
      case 's':
        sampleRate = (unsigned)atoi(optarg);
        break;
      case '0':
        // One of the flags was entered, nothing to do.
        break;
      default:
        break;
    }
  }

  // If no params
  if(argc<=1){
    std::cout << help;
    exit(1);
  }

  // Show help message
  if(showHelp == 1){
    std::cout << help;
    exit(0);
  }

  // show version number
  if(showVersion == 1){
    std::cout << "Normalize version " << VERSION << std::endl;
    exit(0);
  }

  // Validate infile exists
  if(inFilePath.empty()){
    std::cout << "You must provide an input file" << std::endl;
    exit(1);
  }

  std::ifstream inFile(inFilePath.c_str());
  if(!inFile.good()){
    std::cout << "The file " << inFilePath <<" is not valid.\n";
    exit(1);        
  }

  // Validate outFile
  if(outFilePath.empty()){
    std::cout << "You must provide an output file" << std::endl;
    exit(1);
  }
}

//===================//
//  Open Input File  //
//===================//
SNDFILE* openInputFile(){
  SF_INFO inFileInfo;
  SNDFILE *inFile = sf_open(inFilePath.c_str(), SFM_READ, &inFileInfo);
  if(!inFile){
    std::cout << inFilePath << " is not a file I can open.\n";
    exit(1);
  }

  // Set samplerate and format if they have not been specified.
  if(!sampleRate){
    sampleRate = inFileInfo.samplerate;
  }

  minorFormat = inFileInfo.format & SF_FORMAT_SUBMASK;
  if(format.empty()){
    majorFormat = inFileInfo.format & SF_FORMAT_TYPEMASK;
  }
  else if(format == "wav"){
    majorFormat = SF_FORMAT_WAV;
  }
  else if(format == "flac"){
    majorFormat = SF_FORMAT_FLAC;
  }
  else if(format == "au"){
    majorFormat = SF_FORMAT_AU;
  }
  else if(format == "aiff"){
    majorFormat = SF_FORMAT_AIFF;
  }
  else{
    std::cout << "Invalid output format\n";
    exit(1);
  }

  numChannels = inFileInfo.channels;

  return inFile;
}

//====================//
//  Open Output File  //
//====================//
SNDFILE* openOutputFile(){
  SF_INFO outFileInfo;
  outFileInfo.channels = numChannels;
  outFileInfo.format = majorFormat + minorFormat;
  outFileInfo.samplerate = sampleRate;
  SNDFILE *outFile = sf_open(outFilePath.c_str(), SFM_WRITE, &outFileInfo);
  if(!outFile){
    std::cout << "Could not create " << outFilePath << "\n";
    exit(1);
  }

  return outFile;
}

//=============//
//  Normalize  //
//=============//
void normalize(SNDFILE* inFile, SNDFILE* outFile){
  float* buffer = (float*)malloc(BUFFER_LENGTH * numChannels * sizeof(float));

  // First, iterate the whole infile to find the sample with
  // the max value.
  float maxValue = 0;
  sf_count_t count;
  do{
    count = sf_readf_float(inFile, buffer, BUFFER_LENGTH);
    for (int i=0; i<count; i++) {
      float val = fabs( *(buffer+i) );
      if(val > maxValue){
        maxValue = val;
      }
    }
  }while(count);

  // Now, scale proportional to the max value and write to output file.
  sf_seek(inFile, 0, SEEK_SET); // rewind inFile
  float scale = 1.0f / maxValue;
  do{
    count = sf_readf_float(inFile, buffer, BUFFER_LENGTH);
    for (int i=0; i<count; i++) {
      *(buffer+i) = *(buffer+i) * scale;
    }
    sf_writef_float(outFile, buffer, count);
  }while(count);

  sf_write_sync(outFile);
  free(buffer);
}


//========//
//  Main  //
//========//
int main (int argc, char *argv[]) {
  parseParameters(argc, argv);
  SNDFILE *inFile = openInputFile();
  SNDFILE *outFile = openOutputFile();

  #ifdef DEBUG
  std::cout << "format: " << format << std::endl;
  std::cout << "fourmatOut: " << std::hex << majorFormat+minorFormat << std::endl;
  std::cout << "outFile: " << outFilePath << std::endl;
  std::cout << "inFile: " << inFilePath << std::endl;
  std::cout << "sampleRate: " << std::dec << sampleRate << std::endl;
  std::cout << "numChannels: " << numChannels << std::endl;
  #endif

  normalize(inFile, outFile);

  sf_close(inFile);
  sf_close(outFile);

  return 0;
}

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

*

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>