title: Encoding Speex with libavcodec (FFMpeg)?
body: <p>I successfully compiled <strong>libavcodec</strong> with <strong>speex</strong> enabled.
  I modified example from FFMPEG docs to encode the sample audio into Speex.
  But the result file cannot be played with VLC Player(which has Speex decoder).</p>
  
  <p>Any tips?</p>
  
  <pre><code>static void audio_encode_example(const char *filename)
  {
      AVCodec *codec;
      AVCodecContext *c= NULL;
      int frame_size, i, j, out_size, outbuf_size;
      FILE *f;
      short *samples;
      float t, tincr;
      uint8_t *outbuf;
  
      printf("Audio encoding\n");
  
      /* find the MP2 encoder */
      codec = avcodec_find_encoder(CODEC_ID_SPEEX);
      if (!codec) {
          fprintf(stderr, "codec not found\n");
          exit(1);
      }
  
     c= avcodec_alloc_context();
  
      /* put sample parameters */
      c-&gt;bit_rate = 64000;
      c-&gt;sample_rate = 32000;
      c-&gt;channels = 2;
      c-&gt;sample_fmt=AV_SAMPLE_FMT_S16;
  
      /* open it */
      if (avcodec_open(c, codec) &lt; 0) {
          fprintf(stderr, "could not open codec\n");
          exit(1);
      }
  
      /* the codec gives us the frame size, in samples */
      frame_size = c-&gt;frame_size;
      printf("frame size %d\n",frame_size);
      samples =(short*) malloc(frame_size * 2 * c-&gt;channels);
      outbuf_size = 10000;
     outbuf =( uint8_t*) malloc(outbuf_size);
  
      f = fopen(filename, "wb");
      if (!f) {
          fprintf(stderr, "could not open %s\n", filename);
          exit(1);
      }
  
      /* encode a single tone sound */
      t = 0;
      tincr = 2 * M_PI * 440.0 / c-&gt;sample_rate;
      for(i=0;i&lt;200;i++) {
          for(j=0;j&lt;frame_size;j++) {
              samples[2*j] = (int)(sin(t) * 10000);
              samples[2*j+1] = samples[2*j];
              t += tincr;
          }
          /* encode the samples */
          out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);
          fwrite(outbuf, 1, out_size, f);
      }
      fclose(f);
      free(outbuf);
      free(samples);
      avcodec_close(c);
      av_free(c);
  }
  
  int main(int argc, char **argv)
  {
  
      avcodec_register_all();
  
      audio_encode_example(argv[1]);
  
      return 0;
  }
  </code></pre>