Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
2.3 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //=============================================================================//
  7. #undef fopen
  8. #include <stdio.h>
  9. #include "voice_wavefile.h"
  10. // memdbgon must be the last include file in a .cpp file!!!
  11. #include "tier0/memdbgon.h"
  12. static unsigned long ReadDWord(FILE * fp)
  13. {
  14. unsigned long ret;
  15. fread( &ret, 4, 1, fp );
  16. return ret;
  17. }
  18. static unsigned short ReadWord(FILE * fp)
  19. {
  20. unsigned short ret;
  21. fread( &ret, 2, 1, fp );
  22. return ret;
  23. }
  24. static void WriteDWord(FILE * fp, unsigned long val)
  25. {
  26. fwrite( &val, 4, 1, fp );
  27. }
  28. static void WriteWord(FILE * fp, unsigned short val)
  29. {
  30. fwrite( &val, 2, 1, fp );
  31. }
  32. bool ReadWaveFile(
  33. const char *pFilename,
  34. char *&pData,
  35. int &nDataBytes,
  36. int &wBitsPerSample,
  37. int &nChannels,
  38. int &nSamplesPerSec)
  39. {
  40. FILE * fp = fopen(pFilename, "rb");
  41. if(!fp)
  42. return false;
  43. fseek( fp, 22, SEEK_SET );
  44. nChannels = ReadWord(fp);
  45. nSamplesPerSec = ReadDWord(fp);
  46. fseek(fp, 34, SEEK_SET);
  47. wBitsPerSample = ReadWord(fp);
  48. fseek(fp, 40, SEEK_SET);
  49. nDataBytes = ReadDWord(fp);
  50. ReadDWord(fp);
  51. pData = new char[nDataBytes];
  52. if(!pData)
  53. {
  54. fclose(fp);
  55. return false;
  56. }
  57. fread(pData, nDataBytes, 1, fp);
  58. fclose( fp );
  59. return true;
  60. }
  61. bool WriteWaveFile(
  62. const char *pFilename,
  63. const char *pData,
  64. int nBytes,
  65. int wBitsPerSample,
  66. int nChannels,
  67. int nSamplesPerSec)
  68. {
  69. FILE * fp = fopen(pFilename, "wb");
  70. if(!fp)
  71. return false;
  72. // Write the RIFF chunk.
  73. fwrite("RIFF", 4, 1, fp);
  74. WriteDWord(fp, 0);
  75. fwrite("WAVE", 4, 1, fp);
  76. // Write the FORMAT chunk.
  77. fwrite("fmt ", 4, 1, fp);
  78. WriteDWord(fp, 0x10);
  79. WriteWord(fp, 1); // WAVE_FORMAT_PCM
  80. WriteWord(fp, (unsigned short)nChannels);
  81. WriteDWord(fp, (unsigned long)nSamplesPerSec);
  82. WriteDWord(fp, (unsigned long)((wBitsPerSample / 8) * nChannels * nSamplesPerSec));
  83. WriteWord(fp, (unsigned short)((wBitsPerSample / 8) * nChannels));
  84. WriteWord(fp, (unsigned short)wBitsPerSample);
  85. // Write the DATA chunk.
  86. fwrite("data", 4, 1, fp);
  87. WriteDWord(fp, (unsigned long)nBytes);
  88. fwrite(pData, nBytes, 1, fp);
  89. // Go back and write the length of the riff file.
  90. unsigned long dwVal = ftell(fp) - 8;
  91. fseek( fp, 4, SEEK_SET );
  92. WriteDWord(fp, dwVal);
  93. fclose(fp);
  94. return true;
  95. }