WAVEncoder.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "WAVEncoder.h"
  2. #define rev32(X) ((((DWORD)(X)&0xFF)<<24)|(((DWORD)(X)&0xFF00)<<8)|(((DWORD)(X)&0xFF0000)>>8)|(((DWORD)(X)&0xFF000000)>>24))
  3. WAVEncoder::WAVEncoder(int nch, int srate, int bps, ACMConfig *config)
  4. {
  5. numBytes = 0;
  6. inputFormat.wFormatTag = WAVE_FORMAT_PCM;
  7. inputFormat.nChannels = nch;
  8. inputFormat.nSamplesPerSec = srate;
  9. inputFormat.nAvgBytesPerSec = srate * nch * (bps >> 3);
  10. inputFormat.nBlockAlign = nch * (bps >> 3);
  11. inputFormat.wBitsPerSample = bps;
  12. inputFormat.cbSize = 0;
  13. do_header = config->header;
  14. if (do_header)
  15. first = 44;
  16. }
  17. int WAVEncoder::Encode(int framepos, void *in, int in_avail, int *in_used, void *out, int out_avail)
  18. {
  19. if (first)
  20. {
  21. int valid = min(first, out_avail);
  22. first -= valid;
  23. *in_used = 0;
  24. return valid;
  25. }
  26. int valid = min(in_avail, out_avail);
  27. memcpy(out, in, valid);
  28. *in_used = valid;
  29. numBytes += valid;
  30. return valid;
  31. }
  32. void WAVEncoder::PrepareToFinish()
  33. {}
  34. void WAVEncoder::FinishAudio(const wchar_t *filename)
  35. {
  36. if (!do_header) return;
  37. // open old file
  38. HANDLE tempfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  39. if (tempfile)
  40. {
  41. // rewrite initial 44 bytes
  42. DWORD bw = 0;
  43. unsigned __int32 t;
  44. t = rev32('RIFF');
  45. WriteFile(tempfile, &t, 4, &bw, 0); // RIFF (4 bytes)
  46. t = (unsigned __int32)numBytes + 36;
  47. bw = 0;WriteFile(tempfile, &t, 4, &bw, 0); // size of chunk (4 bytes)
  48. t = rev32('WAVE');
  49. bw = 0;WriteFile(tempfile, &t, 4, &bw, 0); // WAVE (4 bytes)
  50. t = rev32('fmt ');
  51. bw = 0;WriteFile(tempfile, &t, 4, &bw, 0);// fmt (4 bytes)
  52. t = 16;
  53. bw = 0;WriteFile(tempfile, &t, 4, &bw, 0);// size of chunk (4 bytes)
  54. bw = 0;WriteFile(tempfile, &inputFormat, 16, &bw, 0); // write WAVEFORMAT out (16 bytes)
  55. t = rev32('data');
  56. bw = 0;WriteFile(tempfile, &t, 4, &bw, 0);// data (4 bytes)
  57. bw = 0;WriteFile(tempfile, &numBytes, 4, &bw, 0);// size of chunk (4 bytes)
  58. CloseHandle(tempfile);
  59. }
  60. }