qm-dsp  1.8
Pitch.cpp
Go to the documentation of this file.
00001 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */
00002 
00003 /*
00004     QM DSP library
00005     Centre for Digital Music, Queen Mary, University of London.
00006     This file Copyright 2006 Chris Cannam.
00007 
00008     This program is free software; you can redistribute it and/or
00009     modify it under the terms of the GNU General Public License as
00010     published by the Free Software Foundation; either version 2 of the
00011     License, or (at your option) any later version.  See the file
00012     COPYING included with this distribution for more information.
00013 */
00014 
00015 #include "Pitch.h"
00016 
00017 #include <math.h>
00018 
00019 float
00020 Pitch::getFrequencyForPitch(int midiPitch,
00021                             float centsOffset,
00022                             float concertA)
00023 {
00024     float p = float(midiPitch) + (centsOffset / 100);
00025     return concertA * powf(2.0, (p - 69.0) / 12.0);
00026 }
00027 
00028 int
00029 Pitch::getPitchForFrequency(float frequency,
00030                             float *centsOffsetReturn,
00031                             float concertA)
00032 {
00033     float p = 12.0 * (log(frequency / (concertA / 2.0)) / log(2.0)) + 57.0;
00034 
00035     int midiPitch = int(p + 0.00001);
00036     float centsOffset = (p - midiPitch) * 100.0;
00037 
00038     if (centsOffset >= 50.0) {
00039         midiPitch = midiPitch + 1;
00040         centsOffset = -(100.0 - centsOffset);
00041     }
00042     
00043     if (centsOffsetReturn) *centsOffsetReturn = centsOffset;
00044     return midiPitch;
00045 }
00046