title: Audio conversion (LAME) C++ WAV -> MP3
body: <p>Good afternoon.
  Sorry, I do not speak very good English.</p>
  
  <p>For some days, I have tried to convert WAV to MP3.
  For that I use LAME.
  I can convert the file through the command prompt with the command:</p>
  
  <pre><code>lame.exe-B128 - resample 8-mj \ "C: \ \ test.wav \" \ "C: \ \ test.mp3 \"
  </code></pre>
  
  <p>but I'd like to not go through a command line (for portability across OSes), but I can’t do it in C++ (via the LAME library).</p>
  
  <p>Here is my code:</p>
  
  <pre><code>int main()
  {
  //...
  //...
  // extraction of PCM audio data file .wav in file.pcm
  short read, write;
  
  FILE *pcm = fopen("file.pcm", "rb");
  FILE *mp3 = fopen("file.mp3", "wb");
  
  const int PCM_SIZE = 18424;
  const int MP3_SIZE = 13424;
  
  short int pcm_buffer[PCM_SIZE];
  unsigned char mp3_buffer[MP3_SIZE];
  
  lame_t lame = lame_init();
  
  if ( lame == NULL ) {
      cout&lt;&lt;"Unable to initialize MP3"&lt;&lt;endl;
      return -1;
  }
  
  lame_set_num_channels(lame, 1);
  lame_set_in_samplerate(lame, 8000);
  lame_set_out_samplerate(lame, 8000);
  lame_set_brate(lame, 128);
  lame_set_mode(lame, MONO);
  lame_set_quality(lame, 2);
  lame_set_bWriteVbrTag(lame, 0);
  if (( lame_init_params(lame)) &lt; 0) {
      cout &lt;&lt; "Unable to initialize MP3 parameters"&lt;&lt;endl;
      return -1;
  }
  
  do {
      read = fread(pcm_buffer,sizeof(short), PCM_SIZE, pcm);
      if (read == 0)
          write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
      else
          write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
      fwrite(mp3_buffer, write, 1, mp3);
  } while (read != 0);
  
  lame_close(lame);
  fclose(mp3);
  fclose(pcm);
  
  return 0;
  }
  </code></pre>
  
  <p>I get an MP3 file of very poor quality (and a shorter duration than the original).</p>
  
  <p>Any ideas to solve the problem?</p>
  
  <p>Here's my info. </p>
  
  <pre><code>Wav:
  - Frequency= 8000
  - BlocSize= 16
  - Canal Nomber= 1 (mono)
  - BytePerSec= 16000
  - BytePerBloc= 2
  - BitsPerSample= 16
  - Bitrate= 128
  - .wav size: 13466 (ie size of PCM: 13422)
  </code></pre>
  
  <p>Thank you.</p>