Advertisement
AntonioVillanueva

Audio Senoidal generador

Nov 8th, 2016
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #define NOMINMAX
  2. #include <windows.h>
  3. #include <iostream>
  4. #include <cmath>
  5. #include <limits>
  6. #include <fstream>
  7. #include <string>
  8.  
  9. typedef signed short                    BitDepth;// 16bit audio
  10. typedef unsigned long long QWORD;
  11.  
  12. const double pi = 3.141592653589;
  13. const DWORD samplerate              =   44100;
  14. const WORD channels                 =   2;
  15. const unsigned short SOUND_DURATION =   1;//    1 second for example.
  16. const QWORD NUM_SAMPLES             =   SOUND_DURATION * samplerate * channels;
  17.  
  18. void sineWave(BitDepth buffer[], double freq) {
  19.     BitDepth amplitude = std::numeric_limits<BitDepth>::max()*0.5;
  20.     QWORD c=0;
  21.     double d=(samplerate/freq);
  22.     for(QWORD i=0; i<NUM_SAMPLES; i+=channels) {
  23.         double deg=360.0/d;
  24.         buffer[i] = buffer[i+(1*(channels-1))] = sin((c++*deg)*pi/180)*amplitude;
  25.     }
  26. }
  27.  
  28. template<typename _Ty> void write(std::ofstream& stream, const _Ty& ty) {
  29.     stream.write((const char*)&ty, sizeof(_Ty));
  30. }
  31.  
  32. void writeWaveFile(const char* filename, BitDepth* buffer) {
  33.     std::ofstream stream(filename, std::ios::binary);
  34.  
  35.     stream.write("RIFF", 4);
  36.     ::write<int>(stream, 36+(NUM_SAMPLES*sizeof(BitDepth)));
  37.     stream.write("WAVEfmt ", 8);
  38.     ::write<int>(stream, 16);
  39.     ::write<short>(stream, 1);
  40.     ::write<unsigned short>(stream, channels);
  41.     ::write<int>(stream, samplerate);
  42.     ::write<int>(stream, samplerate*channels*sizeof(BitDepth));
  43.     ::write<short>(stream, channels*sizeof(BitDepth));
  44.     ::write<short>(stream, sizeof(BitDepth)*8);
  45.     stream.write("data", 4);
  46.     ::write<int>(stream, NUM_SAMPLES*sizeof(BitDepth));
  47.     stream.write((const char*)&buffer[0], NUM_SAMPLES*sizeof(BitDepth));
  48.     stream.close();
  49. }
  50.  
  51. int main(int argc, char** argv) {
  52.     SetConsoleTitleA("PCM Audio Example");
  53.  
  54.     std::string filename = "sine";
  55.  
  56.     BitDepth* buffer = new BitDepth[NUM_SAMPLES];
  57.     memset(buffer, 0, NUM_SAMPLES*sizeof(BitDepth));
  58.  
  59.     sineWave(buffer, 1000.0);
  60.  
  61.  
  62.     writeWaveFile(std::string(filename+std::string(".wav")).c_str(), buffer);
  63.     delete[] buffer;
  64.  
  65.     std::cout << filename << ".wav written!" << std::endl;
  66.     std::cin.get();
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement