Audio plugin host https://kx.studio/carla
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.

93 lines
2.5KB

  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. WavFile.cpp - Wav File Serialization
  4. Copyright (C) 2006 Nasca Octavian Paul
  5. Author: Nasca Octavian Paul
  6. Mark McCurry
  7. This program is free software; you can redistribute it and/or
  8. modify it under the terms of the GNU General Public License
  9. as published by the Free Software Foundation; either version 2
  10. of the License, or (at your option) any later version.
  11. */
  12. #include <cstdio>
  13. #include <cstring>
  14. #include <cstdlib>
  15. #include <iostream>
  16. #include "WavFile.h"
  17. using namespace std;
  18. WavFile::WavFile(string filename, int samplerate, int channels)
  19. :sampleswritten(0), samplerate(samplerate), channels(channels),
  20. file(fopen(filename.c_str(), "w"))
  21. {
  22. if(file) {
  23. cout << "INFO: Making space for wave file header" << endl;
  24. //making space for the header written at destruction
  25. char tmp[44];
  26. memset(tmp, 0, 44 * sizeof(char));
  27. fwrite(tmp, 1, 44, file);
  28. }
  29. }
  30. WavFile::~WavFile()
  31. {
  32. if(file) {
  33. cout << "INFO: Writing wave file header" << endl;
  34. unsigned int chunksize;
  35. rewind(file);
  36. fwrite("RIFF", 4, 1, file);
  37. chunksize = sampleswritten * 4 + 36;
  38. fwrite(&chunksize, 4, 1, file);
  39. fwrite("WAVEfmt ", 8, 1, file);
  40. chunksize = 16;
  41. fwrite(&chunksize, 4, 1, file);
  42. unsigned short int formattag = 1; //uncompresed wave
  43. fwrite(&formattag, 2, 1, file);
  44. unsigned short int nchannels = channels; //stereo
  45. fwrite(&nchannels, 2, 1, file);
  46. unsigned int samplerate_ = samplerate; //samplerate
  47. fwrite(&samplerate_, 4, 1, file);
  48. unsigned int bytespersec = samplerate * 2 * channels; //bytes/sec
  49. fwrite(&bytespersec, 4, 1, file);
  50. unsigned short int blockalign = 2 * channels; //2 channels * 16 bits/8
  51. fwrite(&blockalign, 2, 1, file);
  52. unsigned short int bitspersample = 16;
  53. fwrite(&bitspersample, 2, 1, file);
  54. fwrite("data", 4, 1, file);
  55. chunksize = sampleswritten * blockalign;
  56. fwrite(&chunksize, 4, 1, file);
  57. fclose(file);
  58. file = NULL;
  59. }
  60. }
  61. bool WavFile::good() const
  62. {
  63. return file;
  64. }
  65. void WavFile::writeStereoSamples(int nsmps, short int *smps)
  66. {
  67. if(file) {
  68. fwrite(smps, nsmps, 4, file);
  69. sampleswritten += nsmps;
  70. }
  71. }
  72. void WavFile::writeMonoSamples(int nsmps, short int *smps)
  73. {
  74. if(file) {
  75. fwrite(smps, nsmps, 2, file);
  76. sampleswritten += nsmps;
  77. }
  78. }