comparison audioio/ContinuousSynth.cpp @ 313:58582119c92a tonioni

Add a basic continuous synth implementation (simple sinusoids only, no gaps)
author Chris Cannam
date Wed, 08 Jan 2014 13:07:22 +0000
parents
children 65b75e23bbd5
comparison
equal deleted inserted replaced
312:faee60602049 313:58582119c92a
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
2
3 /*
4 Sonic Visualiser
5 An audio file viewer and annotation editor.
6 Centre for Digital Music, Queen Mary, University of London.
7
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License as
10 published by the Free Software Foundation; either version 2 of the
11 License, or (at your option) any later version. See the file
12 COPYING included with this distribution for more information.
13 */
14
15 #include "ContinuousSynth.h"
16
17 #include "base/Debug.h"
18
19 #include <cmath>
20
21 ContinuousSynth::ContinuousSynth(int channels, int sampleRate, int blockSize) :
22 m_channels(channels),
23 m_sampleRate(sampleRate),
24 m_blockSize(blockSize),
25 m_prevF0(-1.f),
26 m_phase(0.0)
27 {
28 }
29
30 ContinuousSynth::~ContinuousSynth()
31 {
32 }
33
34 void
35 ContinuousSynth::reset()
36 {
37 m_phase = 0;
38 }
39
40 void
41 ContinuousSynth::mix(float **toBuffers, float gain, float pan, float f0)
42 {
43 if (f0 == 0.f) f0 = m_prevF0;
44
45 bool wasOn = (m_prevF0 > 0.f);
46 bool nowOn = (f0 > 0.f);
47
48 if (!nowOn && !wasOn) {
49 m_phase = 0;
50 return;
51 }
52
53 int fadeLength = 20; // samples
54
55 float *levels = new float[m_channels];
56
57 for (int c = 0; c < m_channels; ++c) {
58 levels[c] = gain;
59 }
60 if (pan != 0.0 && m_channels == 2) {
61 levels[0] *= 1.0 - pan;
62 levels[1] *= pan + 1.0;
63 }
64
65 double phasor = (f0 * 2 * M_PI) / m_sampleRate;
66 double p = m_phase;
67
68 cerr << "ContinuousSynth::mix: f0 = " << f0 << " (from " << m_prevF0 << "), phase = " << m_phase << ", phasor = " << phasor << endl;
69
70 for (int i = 0; i < m_blockSize; ++i) {
71
72 p = m_phase + i * phasor;
73
74 double v = sin(p);
75
76 if (!wasOn && i < fadeLength) { // fade in
77 v = v * (i / double(fadeLength));
78 } else if (!nowOn) {
79 if (i > fadeLength) v = 0;
80 else v = v * (1.0 - (i / double(fadeLength)));
81 }
82
83 for (int c = 0; c < m_channels; ++c) {
84 toBuffers[c][i] += levels[c] * v;
85 }
86 }
87
88 m_prevF0 = f0;
89 m_phase = p;
90
91 delete[] levels;
92 }
93