Debian Codegraph @

lib/Music/Scales.pm

raw
1 package Music::Scales;
2 $Music::Scales::VERSION = '0.13';
3 our $AUTHORITY = 'cpan:GENE';
4
5 # ABSTRACT: Generate musical scales
6
7 use strict;
8 use Text::Abbrev;
9
10 BEGIN {
11 use Exporter ();
12 use vars qw($VERSION @ISA @EXPORT);
13 $VERSION = '0.13';
14 @ISA = qw(Exporter);
15 @EXPORT = qw(get_scale_notes get_scale_nums get_scale_offsets is_scale get_scale_PDL get_scale_MIDI %modes %original_modes %abbrevs @scales);
16 }
17
18
19 our %modes = qw(ionian 1 major 1 hypolydian 1 dorian 2 hypomyxolydian 2
20 phrygian 3 hypoaeolian 3 lydian 4 hypolocrian 4 mixolydian 5 hypoionian 5
21 aeolian 6 minor 6 m 6 hypodorian 6 locrian 7 hypophrygian 7
22 harmonicminor 8 hm 8 melodicminor 9 mm 9
23 blues 10 pentatonic 11 pmaj 11 chromatic 12 diminished 13 wholetone 14
24 augmented 15 hungarianminor 16 3semitone 17 4semitone 18
25 neapolitanminor 19 nmin 19 neapolitanmajor 20 nmaj 20
26 todi 21 marva 22 persian 23 oriental 24 romanian 25 pelog 26
27 iwato 27 hirajoshi 28 egyptian 29 pminor 30 pentatonicminor 30
28 );
29 our %original_modes = %modes;
30 our %abbrevs = abbrev(keys %modes);
31 while (my ($k,$v) = each %abbrevs) {
32 $modes{$k} = $modes{$v};
33 }
34
35 our @scales=([0,2,4,5,7,9,11], # Ionian(1)
36 [0,2,3,5,7,9,10], # Dorian (2)
37 [0,1,3,5,7,8,10], # Phrygian (3)
38 [0,2,4,6,7,9,11], # Lydian (4)
39 [0,2,4,5,7,9,10], # Mixolydian (5)
40 [0,2,3,5,7,8,10], # Aeolian (6)
41 [0,1,3,5,6,8,10], # Locrian (7)
42 [0,2,3,5,7,8,11], # Harmonic Minor (8)
43 [0,2,3,5,7,9,11], # Melodic Minor (9)
44 [0,3,5,6,7,10], # Blues (10)
45 [0,2,4,7,9], # Pentatonic (11)
46 [0,1,2,3,4,5,6,7,8,9,10,11],# Chromatic (12)
47 [0,2,3,5,6,8,9,11], # Diminished (13)
48 [0,2,4,6,8,10], # Whole tone(14)
49 [0,3,4,7,8,11], # Augmented (15)
50 [0,2,3,6,7,8,11], # Hungarian minor (16)
51 [0,3,6,9], # 3 semitone (dimished arpeggio) (17)
52 [0,4,8], # 4 semitone (augmented arpeggio) (18)
53 [0,1,3,5,7,8,11], # Neapolitan minor (19)
54 [0,1,3,5,7,9,11], # Neapolitan major (20)
55 [0,1,3,6,7,8,11], # Todi (Indian) (21)
56 [0,1,4,6,7,9,11], # Marva (Indian) (22)
57 [0,1,4,5,6,8,11], # Persian (23)
58 [0,1,4,5,6,9,10], # Oriental (24)
59 [0,2,3,6,7,9,10], # Romanian (25)
60 [0,1,3,7,10], # Pelog (Balinese) (26)
61 [0,1,5,6,10], # Iwato (Japanese) (27)
62 [0,2,3,7,8], # Hirajoshi (Japanese) (28)
63 [0,2,5,7,10], # Egyptian (29)
64 [0,3,5,7,10], # Pentatonic Minor (30)
65 );
66
67 sub get_scale_nums {
68 my ($mode,$descending) = @_;
69 $mode = _get_mode($mode);
70 my @dists = @{$scales[$mode-1]};
71 if ($descending && $mode == 9) {
72 $dists[5]-- ;$dists[6]--;
73 }
74 ($descending) ? reverse @dists : @dists;
75 }
76
77 sub get_scale_offsets {
78 my @scale = get_scale_notes(@_);
79 my %key_alts = qw(C 0 D 0 E 0 F 0 G 0 A 0 B 0);
80 foreach (@scale) {
81 $key_alts{$_}++ if s/#//;
82 $key_alts{$_}-- if s/b//;
83 }
84 %key_alts;
85 }
86
87 sub _get_mode {
88 my $mode = shift() || 1;
89 $mode =~ s/[^a-zA-Z0-9]//g;
90 $mode = $modes{lc($mode)} unless $mode =~/^[0-9]+$/;
91 ($mode && ($mode <= @scales)) ? $mode : 1;
92 }
93
94 sub _note_to_num {
95 my $note = shift();
96 my %note2num = ('A','0','A#','1','BB','1','B','2','C','3','C#','4','DB','4','D','5','D#','6','EB','6','E','7','F','8','F#','9','GB','9','G','10','G#','11','AB','11');
97 return $note if ($note =~/^[0-9]+$/);
98 (defined $note2num{uc($note)}) ? $note2num{uc($note)} : 0;
99 }
100
101 sub _note_to_MIDI {
102 my ($note,$octave) = @_;
103 ((_note_to_num($note)+9) % 12) + (12 * ++$octave );
104 }
105
106 sub get_scale_MIDI {
107 my ($note,$octave,$mode,$descending) = @_;
108 my $basenum = _note_to_MIDI($note,$octave);
109 return map {$basenum + $_} get_scale_nums($mode,$descending);
110 }
111
112 sub get_scale_PDL {
113 my ($note,$octave,$mode,$descending,$keypref) = @_;
114 _scale_to_PDL($octave,get_scale_notes($note,$mode,$descending,$keypref));
115 }
116
117 sub get_scale_notes {
118 my ($keynote,$mode,$descending,$keypref) = @_;
119 my @notes = ('A'..'G');
120 my @nums = (2,1,2,2,1,2,2);
121
122 $keynote =~ s/^[a-z]/\u$&/;
123 $keypref='' unless defined $keypref;
124 my $keynum = _note_to_num(uc($keynote));
125 $mode = _get_mode($mode);
126 my @dists = get_scale_nums($mode,$descending);
127 @dists = reverse @dists if $descending;
128 my @scale = map {($_+$keynum-$dists[0])%12} @dists;
129 $keypref='b' if (!$keypref && $descending && $mode == 12); #prefer flat descending chromatic
130
131 my %num2note = (0,'A',1,'A#',2,'B',3,'C',4,'C#',5,'D',6,'D#',7,'E',8,'F',9,'F#',10,'G',11,'G#');
132 %num2note = (0,'A',1,'Bb',2,'B',3,'C',4,'Db',5,'D',6,'Eb',7,'E',8,'F',9,'Gb',10,'G',11,'Ab') if (($keypref eq 'b') || ($keynote =~ /.b/i));
133 my @mscale = $keynote;
134 if (@scale > 7) { # we're not bothered by niceties, so just convert
135 @mscale = map {$num2note{$_}} @scale;
136 }
137 else {
138 $keynote = $num2note{$keynote} if $keynote =~/^[0-9]+$/;
139 my $kk = $keynote; $kk =~ s/b|\#//; $kk = ord($kk) - ord('A');
140 foreach(0..$kk-1) {# rotate to keynote
141 push @notes,shift(@notes);
142 push @nums,shift(@nums);
143 }
144 push @notes,shift(@notes);
145 shift(@dists);
146 my $cu = shift(@nums);
147 $cu++ if ($keynote =~ /b/);
148 $cu-- if ($keynote =~ /#/);
149 foreach (@dists) {
150 my $m = $_ - $cu;
151 my $ns = shift(@nums);
152 push @nums,$ns;
153 my $n = shift(@notes);
154 push @notes,$n;
155 while (abs($m) > 2 || (@scale < 7 && abs($m) >= $ns)) { # step up/down notes, 'reducing' flats/sharps
156 $n = shift(@notes); push @notes,$n;
157 if ($m > 0) {$m -= $ns;$cu += $ns }
158 elsif ($m < 0){$m += $ns;$cu -= $ns}
159 $ns = shift(@nums); push @nums,$ns;
160 }
161 $n .= '#' x $m if ($m > 0);
162 $n .= 'b' x abs($m) if ($m < 0);
163 push @mscale,$n;
164 $cu += $ns;
165 }
166 }
167 if ($descending) {
168 @mscale = reverse @mscale;
169 unshift @mscale,pop(@mscale);
170 }
171 @mscale;
172 }
173
174
175 sub is_scale {
176 my $name = shift();
177 $name =~ s/[^a-zA-Z0-9]//g;
178 return exists $modes{lc $name} ? 1 : 0;
179 }
180
181 sub _scale_to_PDL {
182 my ($octave,@scale)=@_;
183 my @result;
184 my $descending;
185 my $n1 = _note_to_num($scale[0]);
186 my $n2 = _note_to_num($scale[1]);
187 if ($n2 < $n1 && ($n1-$n2 < 5)) {
188 $descending = 1;
189 @scale = reverse @scale;
190 }
191 my $last = (_note_to_num($scale[0]) + 9) % 12;
192 foreach (@scale) {
193 my $n = (_note_to_num($_) + 9) % 12;
194 $octave++ if ($last > $n); #switched over octave at 'c'
195 s/\#/s/g;
196 s/b/f/g;
197 push @result,lc($_).$octave;
198 $last = $n;
199 }
200 @result = reverse @result if $descending;
201 @result;
202 }
203
204 1;
205
206 __END__
207
208 =pod
209
210 =encoding UTF-8
211
212 =head1 NAME
213
214 Music::Scales - Generate musical scales
215
216 =head1 VERSION
217
218 version 0.13
219
220 =head1 SYNOPSIS
221
222 use Music::Scales qw(get_scale_notes get_scale_MIDI get_scale_PDL get_scale_nums get_scale_offsets is_scale);
223
224 my @maj = get_scale_notes('Eb'); # defaults to major
225 print join(" ",@maj); # "Eb F G Ab Bb C D"
226
227 @maj = get_scale_MIDI('C', 4); # 60, 62, 64, 65, 67, 69, 71
228
229 @maj = get_scale_PDL('Eb', 4); # ef4, f4, g4, af4, bf4, c5, d5
230
231 my @blues = get_scale_nums('bl'); # 'bl','blu','blue','blues'
232 print join(" ",@blues); # "0 3 5 6 7 10"
233
234 my %min = get_scale_offsets('G','mm',1); # descending melodic minor
235 print join " ", map {"$_=$min{$_} "} sort keys %min; # "A=0 B=-1 C=0 D=0 E=-1 F=0 G=0"
236
237 print is_scale('foo') ? 1 : 0;
238
239 =head1 DESCRIPTION
240
241 Given a keynote A-G(#/b) and a scale-name, will return the scale,
242 either as an array of notenames or as a hash of semitone-offsets for each note.
243
244 All functions are exported by default. Also the essential variables,
245 C<%modes>, C<%original_modes>, C<%abbrevs>, and C<@scales> are exported.
246 Please see the source for their definitions.
247
248 =head1 METHODS
249
250 =head2 get_scale_nums($scale[,$descending])
251
252 returns an array of semitone offsets for the requested scale, ascending/descending the given scale for one octave.
253
254 The descending flag determines the direction of the scale, and also affects those scales (such as melodic minor) where the notes vary depending upon the direction.
255
256 Scaletypes and valid values for $scale are listed below.
257
258 =head2 get_scale_notes($notename[,$scale,$descending,$keypref])
259
260 returns an array of notenames, starting from the given keynote.
261
262 Enharmonic equivalencies (whether to use F# or Gb, for instance) are calculated based on the keynote and the scale.
263
264 Basically, it attempts to do the Right Thing if the scale is an 8-note one, (the 7th in G harmonic minor being F# rather than Gb, although G minor is a 'flat' key), but for any other scales, (Chromatic, blues etc.) it picks equivalencies based upon the keynote.
265
266 This can be overidden with $keypref, setting to be either '#' or 'b' for sharps and flats respectively. Cruftiness abounds here :)
267
268 =head2 get_scale_offsets($notename[,$scale,$descending,$keypref])
269
270 as get_scale_notes(), except it returns a hash of notenames with the values being a semitone offset (-1, 0 or 1) as shown in the synopsis.
271
272 =head2 get_scale_MIDI($notename,$octave[,$scale,$descending])
273
274 as get_scale_notes(), but returns an array of MIDI note-numbers, given an octave number (-1..9).
275
276 =head2 get_scale_PDL($notename,$octave[,$scale,$descending])
277
278 as get_scale_MIDI(), but returns an array of PDL-format notes.
279
280 =head2 is_scale($scalename)
281
282 returns true if $scalename is a valid scale name used in this module.
283
284 =head1 SCALES
285
286 Scales can be passed either by name or number.
287
288 The default scale is 'major' if none / invalid is given.
289
290 Text::Abbrev is used on scalenames, so they can be as abbreviated as unambiguously possible ('dor','io' etc.).
291 Other abbreviations are shown in brackets.
292
293 1 ionian / major / hypolydian
294 2 dorian / hypmixolydian
295 3 phrygian / hypoaeolian
296 4 lydian / hypolocrian
297 5 mixolydian / hypoionian
298 6 aeolian / hypodorian / minor / m
299 7 locrian / hypophrygian
300 8 harmonic minor / hm
301 9 melodic minor / mm
302 10 blues
303 11 pentatonic (pmajor)
304 12 chromatic
305 13 diminished
306 14 wholetone
307 15 augmented
308 16 hungarian minor
309 17 3 semitone
310 18 4 semitone
311 19 neapolitan minor (nmin)
312 20 neapolitan major (nmaj)
313 21 todi
314 22 marva
315 23 persian
316 24 oriental
317 25 romanian
318 26 pelog
319 27 iwato
320 28 hirajoshi
321 29 egyptian
322 30 pentatonic minor (pminor)
323
324 =head1 EXAMPLE
325
326 This will print every scale in every key, adjusting the enharmonic equivalents accordingly.
327
328 foreach my $note qw (C C# D D# E F F# G G# A A# B) {
329 foreach my $mode (1..30) {
330 my @notes = get_scale_notes($note,$mode);
331 push @notes, get_scale_notes($note,$mode,1); # descending
332 print join(" ",@notes),"\n";
333 }
334 }
335
336 =head1 TODO
337
338 Add further range of scales from http://www.cs.ruu.nl/pub/MIDI/DOC/scales.zip
339
340 Improve enharmonic equivalents.
341
342 Microtones
343
344 Generate ragas,gamelan etc. - maybe needs an 'ethnic' subset of modules
345
346 =head1 BUGS
347
348 A few enharmonic problems still...
349
350 All feedback most welcome.
351
352 =head1 SEE ALSO
353
354 PDL::Audio::Scale, perl(1).
355
356 =head1 THANK YOU
357
358 Thanks to Steve Hay for pointing out my 'minor' mix-up and many suggestions.
359
360 Thanks also to Gene Boggs for the 'is_scale' suggestion / code.
361
362 =head1 AUTHOR
363
364 Ben Daglish <[email protected]>
365
366 =head1 COPYRIGHT AND LICENSE
367
368 This software is copyright (c) 2003-2026 by Ben Daglish.
369
370 This is free software; you can redistribute it and/or modify it under
371 the same terms as the Perl 5 programming language system itself.
372
373 =cut