Chris@19
|
1 /* -*- c-basic-offset: 4 -*- vi:set ts=8 sts=4 sw=4: */
|
Chris@19
|
2
|
Chris@19
|
3 /*
|
Chris@19
|
4 A waveform viewer and audio annotation editor.
|
Chris@19
|
5 Chris Cannam, Queen Mary University of London, 2005-2006
|
Chris@19
|
6
|
Chris@19
|
7 This is experimental software. Not for distribution.
|
Chris@19
|
8 */
|
Chris@19
|
9
|
Chris@19
|
10 #include "Pitch.h"
|
Chris@19
|
11
|
Chris@19
|
12 #include <cmath>
|
Chris@19
|
13
|
Chris@19
|
14 float
|
Chris@19
|
15 Pitch::getFrequencyForPitch(int midiPitch,
|
Chris@19
|
16 float centsOffset,
|
Chris@19
|
17 float concertA)
|
Chris@19
|
18 {
|
Chris@19
|
19 float p = float(midiPitch) + (centsOffset / 100);
|
Chris@19
|
20 return concertA * powf(2.0, (p - 69.0) / 12.0);
|
Chris@19
|
21 }
|
Chris@19
|
22
|
Chris@19
|
23 int
|
Chris@19
|
24 Pitch::getPitchForFrequency(float frequency,
|
Chris@19
|
25 float *centsOffsetReturn,
|
Chris@19
|
26 float concertA)
|
Chris@19
|
27 {
|
Chris@19
|
28 float p = 12.0 * (log(frequency / (concertA / 2.0)) / log(2.0)) + 57.0;
|
Chris@19
|
29
|
Chris@19
|
30 int midiPitch = int(p + 0.00001);
|
Chris@19
|
31 float centsOffset = (p - midiPitch) * 100.0;
|
Chris@19
|
32
|
Chris@19
|
33 if (centsOffset >= 50.0) {
|
Chris@19
|
34 midiPitch = midiPitch + 1;
|
Chris@19
|
35 centsOffset = -(100.0 - centsOffset);
|
Chris@19
|
36 }
|
Chris@19
|
37
|
Chris@19
|
38 if (centsOffsetReturn) *centsOffsetReturn = centsOffset;
|
Chris@19
|
39 return midiPitch;
|
Chris@19
|
40 }
|
Chris@19
|
41
|
Chris@19
|
42 static QString notes[] = {
|
Chris@19
|
43 "C%1", "C#%1", "D%1", "D#%1",
|
Chris@19
|
44 "E%1", "F%1", "F#%1", "G%1",
|
Chris@19
|
45 "G#%1", "A%1", "A#%1", "B%1"
|
Chris@19
|
46 };
|
Chris@19
|
47
|
Chris@19
|
48 QString
|
Chris@19
|
49 Pitch::getPitchLabel(int midiPitch,
|
Chris@19
|
50 float centsOffset)
|
Chris@19
|
51 {
|
Chris@19
|
52 int octave = -2;
|
Chris@19
|
53
|
Chris@19
|
54 if (midiPitch < 0) {
|
Chris@19
|
55 while (midiPitch < 0) {
|
Chris@19
|
56 midiPitch += 12;
|
Chris@19
|
57 --octave;
|
Chris@19
|
58 }
|
Chris@19
|
59 } else {
|
Chris@19
|
60 octave = midiPitch / 12 - 2;
|
Chris@19
|
61 }
|
Chris@19
|
62
|
Chris@19
|
63 QString plain = notes[midiPitch % 12].arg(octave);
|
Chris@19
|
64
|
Chris@19
|
65 int ic = lrintf(centsOffset);
|
Chris@19
|
66 if (ic == 0) return plain;
|
Chris@19
|
67 else if (ic > 0) return QString("%1+%2c").arg(plain).arg(ic);
|
Chris@19
|
68 else return QString("%1%2c").arg(plain).arg(ic);
|
Chris@19
|
69 }
|
Chris@19
|
70
|
Chris@19
|
71 QString
|
Chris@19
|
72 Pitch::getPitchLabelForFrequency(float frequency,
|
Chris@19
|
73 float concertA)
|
Chris@19
|
74 {
|
Chris@19
|
75 float centsOffset = 0.0;
|
Chris@19
|
76 int midiPitch = getPitchForFrequency(frequency, ¢sOffset, concertA);
|
Chris@19
|
77 return getPitchLabel(midiPitch, centsOffset);
|
Chris@19
|
78 }
|
Chris@19
|
79
|