8 #include "linux_audio.h"
9 #include "pitchdetector.h"
11 void print_spectrogram(double freq, double amp);
12 void write_sine(int dsp_fd, double freq, unsigned num_samples);
16 PitchDetector pd(SAMPLE_RATE, FFT_LENGTH, PAD_FACTOR, OVERLAP);
17 int fd = get_dsp_fd(SAMPLE_RATE, FFT_LENGTH, OVERLAP);
19 short buf[FFT_LENGTH / PAD_FACTOR / OVERLAP];
21 read_chunk(fd, buf, FFT_LENGTH / PAD_FACTOR / OVERLAP);
22 std::pair<double, double> peak = pd.detect_pitch(buf);
24 if (peak.first < 50.0 || peak.second - log10(FFT_LENGTH) < 0.0) {
25 #if TUNING == WELL_TEMPERED_GUITAR
28 printf("............\n");
31 print_spectrogram(peak.first, peak.second - log10(FFT_LENGTH));
36 std::string freq_to_tonename(double freq)
38 std::string notenames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
39 double half_notes_away = 12.0 * log2(freq / BASE_PITCH) - 3.0;
40 int hnai = int(floor(half_notes_away + 0.5));
41 int octave = (hnai + 48) / 12;
44 sprintf(buf, "%s%d + %.2f [%d]", notenames[((hnai % 12) + 12) % 12].c_str(), octave, half_notes_away - hnai, hnai);
48 #if TUNING == EQUAL_TEMPERAMENT
49 void print_spectrogram(double freq, double amp)
51 std::string notenames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
52 double half_notes_away = 12.0 * log2(freq / BASE_PITCH) - 3.0;
53 int hnai = int(floor(half_notes_away + 0.5));
54 int octave = (hnai + 48) / 12;
56 for (int i = 0; i < 12; ++i)
57 if (i == ((hnai % 12) + 12) % 12)
62 printf(" (%-2s%d %+.2f, %5.2fHz) [%5.2fdB] [", notenames[((hnai % 12) + 12) % 12].c_str(), octave, half_notes_away - hnai,
65 double off = half_notes_away - hnai;
66 for (int i = -10; i <= 10; ++i) {
67 if (off >= (i-0.5) * 0.05 && off < (i+0.5) * 0.05) {
85 static note notes[] = {
86 { "E-3", BASE_PITCH/4.0 * (3.0/4.0) },
87 { "A-3", BASE_PITCH/4.0 },
88 { "D-4", BASE_PITCH/4.0 * (4.0/3.0) },
89 { "G-4", BASE_PITCH/4.0 * (4.0/3.0)*(4.0/3.0) },
90 { "B-4", BASE_PITCH * (3.0/4.0)*(3.0/4.0) },
91 { "E-5", BASE_PITCH * (3.0/4.0) }
94 void print_spectrogram(double freq, double amp)
96 double best_away = 999999999.9;
97 unsigned best_away_ind = 0;
99 for (unsigned i = 0; i < sizeof(notes)/sizeof(note); ++i) {
100 double half_notes_away = 12.0 * log2(freq / notes[i].freq);
101 if (fabs(half_notes_away) < fabs(best_away)) {
102 best_away = half_notes_away;
107 for (unsigned i = 0; i < sizeof(notes)/sizeof(note); ++i)
108 if (i == best_away_ind)
113 printf(" (%s %+.2f, %5.2fHz) [%5.2fdB] [", notes[best_away_ind].notename, best_away, freq, amp);
116 for (int i = -10; i <= 10; ++i) {
117 if (best_away >= (i-0.5) * 0.05 && best_away < (i+0.5) * 0.05) {
130 for (int i = -10; i <= 10; ++i) {
131 if (best_away >= (i-0.5) * 0.01 && best_away < (i+0.5) * 0.01) {