sampleenc.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <speex/speex.h>
  2. #include <stdio.h>
  3. /*The frame size in hardcoded for this sample code but it doesn't have to be*/
  4. #define FRAME_SIZE 160
  5. int main(int argc, char **argv)
  6. {
  7. char *inFile;
  8. FILE *fin;
  9. short in[FRAME_SIZE];
  10. float input[FRAME_SIZE];
  11. char cbits[200];
  12. int nbBytes;
  13. /*Holds the state of the encoder*/
  14. void *state;
  15. /*Holds bits so they can be read and written to by the Speex routines*/
  16. SpeexBits bits;
  17. int i, tmp;
  18. /*Create a new encoder state in narrowband mode*/
  19. state = speex_encoder_init(&speex_nb_mode);
  20. /*Set the quality to 8 (15 kbps)*/
  21. tmp=8;
  22. speex_encoder_ctl(state, SPEEX_SET_QUALITY, &tmp);
  23. if (argc < 2)
  24. return 1;
  25. inFile = argv[1];
  26. fin = fopen(inFile, "r");
  27. /*Initialization of the structure that holds the bits*/
  28. speex_bits_init(&bits);
  29. while (1)
  30. {
  31. /*Read a 16 bits/sample audio frame*/
  32. fread(in, sizeof(short), FRAME_SIZE, fin);
  33. if (feof(fin))
  34. break;
  35. /*Copy the 16 bits values to float so Speex can work on them*/
  36. for (i=0;i<FRAME_SIZE;i++)
  37. input[i]=in[i];
  38. /*Flush all the bits in the struct so we can encode a new frame*/
  39. speex_bits_reset(&bits);
  40. /*Encode the frame*/
  41. speex_encode(state, input, &bits);
  42. /*Copy the bits to an array of char that can be written*/
  43. nbBytes = speex_bits_write(&bits, cbits, 200);
  44. /*Write the size of the frame first. This is what sampledec expects but
  45. it's likely to be different in your own application*/
  46. fwrite(&nbBytes, sizeof(int), 1, stdout);
  47. /*Write the compressed data*/
  48. fwrite(cbits, 1, nbBytes, stdout);
  49. }
  50. /*Destroy the encoder state*/
  51. speex_encoder_destroy(state);
  52. /*Destroy the bit-packing struct*/
  53. speex_bits_destroy(&bits);
  54. fclose(fin);
  55. return 0;
  56. }