title: C, or C++ code for using LAME API to convert an M4A (MPEG-4 audio) to MP3
body: <p>I'm using native LAME code for a part of my Android application. This code is supposed to take a string pointing to the input file (M4A) and a string to the output file (MP3). I found some code that seems, from what I can gather, to do such a thing. However, when I play back the MP3 files, all I hear is a ZIP! sound. No matter how long the recording is, I get the same sound.</p>
  
  <p>I was thinking that this had something to do with the sample rate, so I've tried all of the standard ones, and get nearly the same result (some zips are less... zippy).</p>
  
  <p>Here is the the only C code that I've been able to find, however, I'm open to using a C++ solution, as well.</p>
  
  <pre><code>#include &lt;jni.h&gt;  
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;android/log.h&gt;
  #include "lame.h"
  
  #define DEBUG_TAG "WBA"  
  
  void Java_net_smartnotes_media_RawAudioRecorder_transcode(JNIEnv * env, jobject this, jstring from, jstring to) {
      jboolean isCopy;  
      const char * szFrom = (*env)-&gt;GetStringUTFChars(env, from, &amp;isCopy);
      const char * szTo = (*env)-&gt;GetStringUTFChars(env, to, &amp;isCopy);
  
      __android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK:LC: [%s]", szFrom);
      __android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK:LC: [%s]", szTo);
  
      int read, write;
  
      FILE *pcm = fopen(szFrom, "rb");
      FILE *mp3 = fopen(szTo, "wb");
  
      const int PCM_SIZE = 8192;
      const int MP3_SIZE = 8192;
  
      short int pcm_buffer[PCM_SIZE*2];
      unsigned char mp3_buffer[MP3_SIZE];
  
      lame_t lame = lame_init();
      lame_set_in_samplerate(lame, 44100);
      lame_set_VBR(lame, vbr_default);
      lame_init_params(lame);
  
      do {
          read = fread(pcm_buffer, 2*sizeof(short int), 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);
  
      (*env)-&gt;ReleaseStringUTFChars(env, from, szFrom);
      (*env)-&gt;ReleaseStringUTFChars(env, to, szTo); 
   }
  </code></pre>