@@ -36,12 +36,17 @@ void AudioSynthDevice::start(int hzFreq)
3636{
3737 reset ();
3838 mPos = 0 ;
39- newCall = true ;
4039 mHzFreq = hzFreq;
40+
41+ mOmega = mHzFreq * M_PI / mSampleRate ;
42+ mY1 = -std::sin (mOmega ) * M;
43+ mY2 = -std::sin (2 * mOmega ) * M;
44+ mB = 2.0 * cos (mOmega ) * M;
45+
4146 if (mBuffered ) {
4247 const qint64 length = (mSampleRate * (mSampleSize / 8 ));
4348 mBuffer .resize (length);
44- generate (mBuffer .data (), length, hzFreq );
49+ generate (mBuffer .data (), length);
4550 }
4651 emit readyRead ();
4752}
@@ -52,39 +57,28 @@ void AudioSynthDevice::stop()
5257 mHzFreq = 0 ;
5358}
5459
55- // Modefied coupled first-order form algorithm with fixed point arithmetic
56- int AudioSynthDevice::generate (char *data, int length, int hzFreq )
60+ // Modified coupled first-order form algorithm with fixed point arithmetic
61+ int AudioSynthDevice::generate (char *data, int length)
5762{
58- if (hzFreq == 0 ) return 0 ;
59-
63+ if (mHzFreq == 0 )
64+ return 0 ;
65+
6066 const int channelBytes = mSampleSize / 8 ;
6167
62- qint64 maxlen = length / channelBytes;
68+ const qint64 maxlen = length / channelBytes;
6369
64- static const int M = 1 << 30 ;
65- const auto w = hzFreq * M_PI / mSampleRate ;
66- const long long b1 = 2.0 * cos (w) * M;
67- static const int AMPLITUDE = (1 << (mSampleSize - 1 )) - 1 ;
70+ const int AMPLITUDE = (1 << (mSampleSize - 1 )) - 1 ;
6871
6972 unsigned char *ptr = reinterpret_cast <unsigned char *>(data);
7073
71- // Need to save values between readData(...) calls, so static
72- static long long y0 = 0 ;
73- static decltype (y0) y1 = 0 ;
74- static decltype (y0) y2 = 0 ;
75-
76- if (newCall) {
77- y1 = M * std::sin (-w);
78- y2 = M * std::sin (-2 * w);
79- newCall = false ;
80- }
74+ long long y0;
8175
8276 int i = 0 ;
8377
8478 for (i = 0 ; i < maxlen; ++i) {
85- y0 = b1 * y1 / M - y2 ;
86- y2 = b1 * y0 / M - y1 ;
87- y1 = b1 * y2 / M - y0;
79+ y0 = mB * mY1 / M - mY2 ;
80+ mY2 = mB * y0 / M - mY1 ;
81+ mY1 = mB * mY2 / M - y0;
8882
8983 if (mSampleSize == 8 ) {
9084 const qint8 val = static_cast <qint8>(y0 * AMPLITUDE / M);
@@ -113,7 +107,7 @@ qint64 AudioSynthDevice::readData(char *data, qint64 len)
113107
114108 return total;
115109 } else {
116- return generate (data, len, mHzFreq );
110+ return generate (data, len);
117111 }
118112}
119113
0 commit comments