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.

97 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. namespace zyncarla {
  19. WavFile::WavFile(string filename, int samplerate, int channels)
  20. :sampleswritten(0), samplerate(samplerate), channels(channels),
  21. file(fopen(filename.c_str(), "w"))
  22. {
  23. if(file) {
  24. cout << "INFO: Making space for wave file header" << endl;
  25. //making space for the header written at destruction
  26. char tmp[44];
  27. memset(tmp, 0, 44 * sizeof(char));
  28. fwrite(tmp, 1, 44, file);
  29. }
  30. }
  31. WavFile::~WavFile()
  32. {
  33. if(file) {
  34. cout << "INFO: Writing wave file header" << endl;
  35. unsigned int chunksize;
  36. rewind(file);
  37. fwrite("RIFF", 4, 1, file);
  38. chunksize = sampleswritten * 4 + 36;
  39. fwrite(&chunksize, 4, 1, file);
  40. fwrite("WAVEfmt ", 8, 1, file);
  41. chunksize = 16;
  42. fwrite(&chunksize, 4, 1, file);
  43. unsigned short int formattag = 1; //uncompresed wave
  44. fwrite(&formattag, 2, 1, file);
  45. unsigned short int nchannels = channels; //stereo
  46. fwrite(&nchannels, 2, 1, file);
  47. unsigned int samplerate_ = samplerate; //samplerate
  48. fwrite(&samplerate_, 4, 1, file);
  49. unsigned int bytespersec = samplerate * 2 * channels; //bytes/sec
  50. fwrite(&bytespersec, 4, 1, file);
  51. unsigned short int blockalign = 2 * channels; //2 channels * 16 bits/8
  52. fwrite(&blockalign, 2, 1, file);
  53. unsigned short int bitspersample = 16;
  54. fwrite(&bitspersample, 2, 1, file);
  55. fwrite("data", 4, 1, file);
  56. chunksize = sampleswritten * blockalign;
  57. fwrite(&chunksize, 4, 1, file);
  58. fclose(file);
  59. file = NULL;
  60. }
  61. }
  62. bool WavFile::good() const
  63. {
  64. return file;
  65. }
  66. void WavFile::writeStereoSamples(int nsmps, short int *smps)
  67. {
  68. if(file) {
  69. fwrite(smps, nsmps, 4, file);
  70. sampleswritten += nsmps;
  71. }
  72. }
  73. void WavFile::writeMonoSamples(int nsmps, short int *smps)
  74. {
  75. if(file) {
  76. fwrite(smps, nsmps, 2, file);
  77. sampleswritten += nsmps;
  78. }
  79. }
  80. }