sampleenc.c 1.77 KB
Newer Older
1
#include <speex/speex.h>
2 3
#include <stdio.h>

jm's avatar
jm committed
4
/*The frame size in hardcoded for this sample code but it doesn't have to be*/
5 6 7 8 9 10 11 12 13
#define FRAME_SIZE 160
int main(int argc, char **argv)
{
   char *inFile;
   FILE *fin;
   short in[FRAME_SIZE];
   float input[FRAME_SIZE];
   char cbits[200];
   int nbBytes;
jm's avatar
jm committed
14
   /*Holds the state of the encoder*/
15
   void *state;
jm's avatar
jm committed
16
   /*Holds bits so they can be read and written to by the Speex routines*/
17 18 19
   SpeexBits bits;
   int i, tmp;

jm's avatar
jm committed
20
   /*Create a new encoder state in narrowband mode*/
21 22
   state = speex_encoder_init(&speex_nb_mode);

jm's avatar
jm committed
23
   /*Set the quality to 8 (15 kbps)*/
24 25 26 27 28 29
   tmp=8;
   speex_encoder_ctl(state, SPEEX_SET_QUALITY, &tmp);

   inFile = argv[1];
   fin = fopen(inFile, "r");

jm's avatar
jm committed
30
   /*Initialization of the structure that holds the bits*/
31 32 33
   speex_bits_init(&bits);
   while (1)
   {
jm's avatar
jm committed
34
      /*Read a 16 bits/sample audio frame*/
35 36 37
      fread(in, sizeof(short), FRAME_SIZE, fin);
      if (feof(fin))
         break;
jm's avatar
jm committed
38
      /*Copy the 16 bits values to float so Speex can work on them*/
39 40
      for (i=0;i<FRAME_SIZE;i++)
         input[i]=in[i];
jm's avatar
jm committed
41 42

      /*Flush all the bits in the struct so we can encode a new frame*/
43 44
      speex_bits_reset(&bits);

jm's avatar
jm committed
45
      /*Encode the frame*/
46
      speex_encode(state, input, &bits);
jm's avatar
jm committed
47
      /*Copy the bits to an array of char that can be written*/
48 49
      nbBytes = speex_bits_write(&bits, cbits, 200);

jm's avatar
jm committed
50 51
      /*Write the size of the frame first. This is what sampledec expects but
       it's likely to be different in your own application*/
52
      fwrite(&nbBytes, sizeof(int), 1, stdout);
jm's avatar
jm committed
53
      /*Write the compressed data*/
54
      fwrite(cbits, 1, nbBytes, stdout);
Tristan Matthews's avatar
Tristan Matthews committed
55

56
   }
Tristan Matthews's avatar
Tristan Matthews committed
57

jm's avatar
jm committed
58
   /*Destroy the encoder state*/
59
   speex_encoder_destroy(state);
jm's avatar
jm committed
60
   /*Destroy the bit-packing struct*/
61 62 63 64
   speex_bits_destroy(&bits);
   fclose(fin);
   return 0;
}