aboutsummaryrefslogtreecommitdiff
path: root/freqnote.pl
blob: eaf68abc0ad95c6b337257a8f4c3bd3456154233 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/perl -w

# convert a frequency to a note name.
# formula came from http://en.wikipedia.org/wiki/Note
# p = 69 + 12 * log2(f/440)
# ...where f is in Hz and p is the MIDI note number

@notenames = (
		'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'
		);

sub log2 {
	return log($_[0])/log(2);
}

sub midi2note {
	my $pitch = int(shift);
	my $class = $notenames[$pitch % 12];
	my $octave = int($pitch / 12) - 1;
	return $class . $octave;
}

for(@ARGV) {
	my $p = 69 + 12 * log2($_ / 440);
	my $pitch = int($p);
	my $cents = int(($p - $pitch) * 1000)/10;
	if($cents > 50) {
		$pitch++;
		$cents = $cents - 100;
	}
	if($cents == 0) {
		$cents = "";
	} elsif($cents > 0) {
		$cents = "+$cents" . "c";
	} else {
		$cents .= "c";
	}
	print $_ . "Hz = MIDI $pitch = " . midi2note($pitch) . " $cents\n";
}