tone.cpp

Go to the documentation of this file.
00001 #include <math.h>
00002 #include "basic_source.h"
00003 #include "internal.h"
00004 #include "types.h"
00005 
00006 namespace audiere {
00007 
00008   static const double PI = 3.14159265358979323846;
00009 
00010   class SineWave : public BasicSource {
00011   public:
00012     SineWave(double frequency) {
00013       m_frequency = frequency;
00014       doReset(); // not supposed to call virtual functions in constructors
00015     }
00016 
00017     void ADR_CALL getFormat(
00018       int& channel_count,
00019       int& sample_rate,
00020       SampleFormat& sample_format)
00021     {
00022       channel_count = 1;
00023       sample_rate   = 44100;
00024       sample_format = SF_S16;
00025     }
00026 
00027     int doRead(int frame_count, void* buffer) {
00028       // if frequency is 0 Hz, use silence
00029       if (m_frequency == 0) {
00030         memset(buffer, 0, frame_count * 2);
00031         return frame_count;
00032       }
00033 
00034       s16* out = (s16*)buffer;
00035       for (int i = 0; i < frame_count; ++i) {
00036         double h = sin(2 * PI * m_frequency / 44100 * elapsed++);
00037         out[i] = normal_to_s16(h);
00038       }
00039       return frame_count;
00040     }
00041 
00042     void ADR_CALL reset() {
00043       doReset();
00044     }
00045 
00046   private:
00047     void doReset() {
00048       elapsed = 0;
00049     }
00050 
00051     s16 normal_to_s16(double d) {
00052       d = (d + 1) / 2; // convert from [-1, 1] to [0, 1]
00053       return s16(d * 32767 - 16384);
00054     }
00055 
00056     double m_frequency;
00057     long elapsed;
00058   };
00059 
00060 
00061   ADR_EXPORT(SampleSource*) AdrCreateTone(double frequency) {
00062     return new SineWave(frequency);
00063   }
00064 
00065 }

Generated on Mon Feb 13 23:07:47 2006 for audiere by  doxygen 1.4.6