plectrum

Plectrum: instrument tuner for Android
Log | Files | Refs | README | LICENSE

PitchComparator.java (1507B)


      1 package com.github.cythara;
      2 
      3 import com.github.cythara.tuning.NoteFrequencyCalculator;
      4 
      5 import java.util.Arrays;
      6 
      7 class PitchComparator {
      8 
      9     static PitchDifference retrieveNote(float pitch) {
     10         Tuning tuning = MainActivity.getCurrentTuning();
     11         int referencePitch = MainActivity.getReferencePitch();
     12 
     13         Note[] tuningNotes = tuning.getNotes();
     14         Note[] notes;
     15 
     16         if (MainActivity.isAutoModeEnabled()) {
     17             notes = tuningNotes;
     18         } else {
     19             notes = new Note[]{tuningNotes[MainActivity.getReferencePosition()]};
     20         }
     21 
     22         NoteFrequencyCalculator noteFrequencyCalculator =
     23                 new NoteFrequencyCalculator(referencePitch);
     24 
     25         Arrays.sort(notes, (o1, o2) ->
     26                 Double.compare(noteFrequencyCalculator.getFrequency(o1),
     27                         noteFrequencyCalculator.getFrequency(o2)));
     28 
     29         double minCentDifference = Float.POSITIVE_INFINITY;
     30         Note closest = notes[0];
     31         for (Note note : notes) {
     32             double frequency = noteFrequencyCalculator.getFrequency(note);
     33             double centDifference = 1200d * log2(pitch / frequency);
     34 
     35             if (Math.abs(centDifference) < Math.abs(minCentDifference)) {
     36                 minCentDifference = centDifference;
     37                 closest = note;
     38             }
     39         }
     40 
     41         return new PitchDifference(closest, minCentDifference);
     42     }
     43 
     44     private static double log2(double number) {
     45         return Math.log(number) / Math.log(2);
     46     }
     47 }