| 176 | } |
| 177 | |
| 178 | static int _synth(int frequency, float amplitude, short* sample_buf, |
| 179 | int samples) { |
| 180 | int i; |
| 181 | |
| 182 | for (i = 0; i < samples; i++) { |
| 183 | float t = i / (float)SAMPLES_PER_SEC; |
| 184 | float v; |
| 185 | if (frequency > 0) { |
| 186 | v = amplitude * sin(frequency * t * 2 * M_PI) + |
| 187 | (amplitude * 0.1f) * sin(frequency * 2 * t * 2 * M_PI); |
| 188 | } else { |
| 189 | int r = rand(); |
| 190 | r = r > 0 ? r : -r; |
| 191 | v = amplitude * (-0.5f + (r % 1024) / 512.0f); |
| 192 | } |
| 193 | int value = (int)(v * 32768.0f); |
| 194 | sample_buf[i] = value < -32767 ? -32767 : value > 32767 ? 32767 : value; |
| 195 | |
| 196 | if (i > 0 && sample_buf[i - 1] < 0 && sample_buf[i] >= 0) { |
| 197 | // start of new wave -- check if we have room for a full period of it |
| 198 | int period_samples = (1.0f / frequency) * SAMPLES_PER_SEC; |
| 199 | if (i + period_samples >= samples) break; |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | return i; |
| 204 | } |
| 205 | |
| 206 | static void _taper(short* sample_buf, int samples) { |
| 207 | int i; |