-
Notifications
You must be signed in to change notification settings - Fork 116
/
guitarflash.py
executable file
·472 lines (387 loc) · 13.1 KB
/
guitarflash.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#!/usr/bin/env python3
"""A program to help with practicing guitar.
Can run a metronome, play notes, display guitar tablature for notes,
and give several types of flashcard-style quiz.
Copyright 2024 by Akkana: share and enjoy under the GPLv2 or later.
"""
# Uses chord display code and fret notation adapted from
# https://www.101computing.net/guitar-chords-reader/
import subprocess
import random
import re
import argparse
import time
import xdg.BaseDirectory
import os, sys
try:
import pyfiglet
except:
print("pyfiglet isn't available: can't draw big chord names")
# If there's no GUITARFLASH env variable or ~/.config/guitarflash.conf,
# show only these chords (space separated):
BEGINNER_CHORDS = "D A E"
# How many times to repeat each note or chord that's played
REPEAT_PLAY = 2
# A Python Dictionary matching chord names with "fret notation"
GUITAR_CHORDS = {
"D": "xx0232",
"A": "x02220",
"E": "022100",
"G": "320003",
"C": "x32010",
"F": "x3321x",
"Am": "x02210",
"Dm": "xx0231",
"Em": "022000",
"G2": "320033",
# "stuck 3-4 chords:
"bigG": "32oo22",
"rockG": "3xoo33",
"Cadd9": "x32o33",
# "Cadd9": "x32o3o",
"Dsus4": "xxo233",
"A7sus4": "xo2233",
"Emin7": "022033",
"Dadd11": "2xo233",
"F69": "xx3233",
# 7s
"Fmaj7": "xx3210",
"Fmaj7C": "x33210",
"B7": "o212o2",
"D7": "'xxo212",
"G7": "32ooo1",
"B7": "o212o1",
"E7": "o2o1oo",
"A7": "xo2o2o",
# 6
"F6": "13o2xx",
"B": "x24442",
"F": "133211",
"miniF": "xx3211",
"F#m": "244222",
"F#m": "244222"
}
# Notes must start with C: in sox, A2 is higher than C2
# so a scale goes C2, D2 ... G2, A2, B2, C2, D3 ...
# Use sharps rather than flats for the notes.
basicnotes = [ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ]
ALLNOTES = [ note + '2' for note in basicnotes ] + \
[ note + '3' for note in basicnotes ] + \
[ note + '4' for note in basicnotes ]
GUITAR_STRINGS = [ "E2", "A2", "D3", "G3", "B3", "E4" ]
#
# Build the individual note dictionary.
# Keys are note names ("A2"), values are (string, fret) pairs.
# The string number is 0 for low E2, 5 for high E4,
# NOT standard guitar string numbering that starts at the high string.
#
NOTE2STRING = {} # will be filled by initialize()
# How slowly to "strum" a chord
DELAY_BETWEEN_STRINGS = .06
Volume = 1
Metroproc = None
def initialize():
for stringno, note in enumerate(GUITAR_STRINGS):
fret = 0
NOTE2STRING[note] = (stringno, 0)
while True:
note = up_one_semitone(note)
fret += 1
# We're done with this string if the new note equals the base
# note (fret 0) on the next string,
# OR if this is the last string and we've done enough frets.
if stringno < len(GUITAR_STRINGS) - 1:
if note == GUITAR_STRINGS[stringno+1]:
break
else: # last string
if fret > 4:
break
# If neither of those two conditions was satisfied,
# stay on this string and add the note.
NOTE2STRING[note] = (stringno, fret)
def up_one_semitone(note):
"""Given a note like "C2", return the designation
for one semitone higher, "C#2"
"""
noteletter = note[0] # "C"
noteoctave = note[-1] # '2'
# Is it already sharp?
if note[1] == '#':
if noteletter == 'G':
return 'A' + noteoctave
return chr(ord(noteletter) + 1) + noteoctave
# Okay, not sharp.
# Special case: B->C is where the octave number changes,
# and B can't be sharpened, so return C of the next octave
if noteletter == 'B':
return 'C%d' % (int(noteoctave) + 1)
# E is the other note that can't be sharpened.
if noteletter == 'E':
return 'F' + noteoctave
# Sharpen the current note in the same octave
return noteletter + "#" + noteoctave
def fretboard_to_note(stringbase, fret):
stringnote = ALLNOTES.index(stringbase)
# print("string", stringbase, "fret", fret,
# "->", ALLNOTES[stringnote + fret])
return ALLNOTES[stringnote + fret]
def chord_to_notes(chord_tab):
"""Take notation like "xx0232" and turn it into a list of notes like E2
"""
chord_notes = []
for stringno, string_fret in enumerate(chord_tab):
if string_fret == 'x' or string_fret == ' ':
continue
chord_notes.append(fretboard_to_note(GUITAR_STRINGS[stringno],
int(string_fret)))
return chord_notes
def display_note(note):
"""Use NOTE2STRING to display notes as tablature
"""
stringno, fret = NOTE2STRING[note]
print("string", stringno+1, "fret", fret)
#
line = ''
for stringNo in range(6):
if stringno == stringNo and fret == 0:
line += ' O'
else:
line += ' -'
print(line)
#
if fret > 5:
maxfret = fret
else:
maxfret = 5
#
for fretNo in range(1, maxfret):
line = ""
for stringNo in range(6):
if stringno == stringNo and fret == fretNo:
line += " #"
else:
line += " |"
print(line)
def display_chord(chord):
"""Given a chord name like 'A2', print a tablature for it.
"""
try:
fretNotation = GUITAR_CHORDS[chord]
except KeyError:
print("Don't know the", chord, "chord", file=sys.stderr)
return
print(" " + chord)
nut = ""
for string in fretNotation:
if string == "x":
nut = nut + " x" # x means don't play this string
else:
nut = nut + " _"
print(nut)
for fretNumber in range(1, 5):
fret = ""
for string in fretNotation:
if string == str(fretNumber):
fret = fret + " O"
else:
fret = fret + " |"
print(fret)
def play_chord(chordname):
"""Play a chord, specified by name like "Em".
"""
args = [ "play", "-nq", "-t", "alsa", "synth" ]
# pl G2 pl B2 pl D3 pl G3 pl D4 pl G4 \
# delay 0 .05 .1 .15 .2 .25 remix - fade 0 4 .1 norm -1
chordnotes = chord_to_notes(GUITAR_CHORDS[chordname])
for note in chordnotes:
args.append("pl")
args.append(note)
args.append("delay")
delay = 0
for ch in chordnotes:
args.append(str(delay))
delay += DELAY_BETWEEN_STRINGS
args += [ "remix", "-",
"fade", "0", str(delay + 1.5), ".1",
"norm", "-1", "vol", str(Volume) ]
# print(' '.join(args))
subprocess.call(args)
def play_notes(notestr, delay=.6):
"""Play a sequence of notes, comma separated, e.g. "C1,C2,C3"
with a single sox play command.
Useful for testing.
"""
notes = notestr.split(',')
args = [ "play", "-nq", "-t", "alsa", "synth" ]
for note in notes:
args.append("pl")
args.append(note)
args.append("delay")
d = 0
for note in notes:
args.append(str(d))
d += delay
args += [ "remix", "-",
"fade", "0", str(len(notes) * delay + 2), ".1",
"norm", "-1", "vol", str(Volume) ]
# print(' '.join(args))
subprocess.call(args)
def start_metronome(bpm, duration=None):
global Metroproc
args = [ "play", "-nq", "-t", "alsa",
"-c1", "synth", "0.004", "sine", "2000",
"pad", str(60/bpm -.004),
"repeat", str(bpm * duration) if duration else '-',
"vol", str(Volume) ]
print(args)
Metroproc = subprocess.Popen(args, close_fds=True)
def stop_metronome():
global Metroproc
if not Metroproc:
# print("Metronome isn't running")
return
print("Stopping metronome")
Metroproc.kill()
Metroproc = None
def sanity_check(chords):
"""Do all the indicated chords actually exist?"""
goodchords = []
badchords = set()
for c in chords:
if c in GUITAR_CHORDS:
goodchords.append(c)
else:
badchords.add(c)
if badchords:
print("Ignoring unsupported chords", ' '.join(badchords))
if not goodchords:
print("No chords left; defaulting to beginner chords")
return BEGINNER_CHORDS,
return goodchords
def bigtext(s):
if 'pyfiglet' in sys.modules:
return pyfiglet.figlet_format(s)
return "=== " + s
lastchord = None
def chord_flashcard(chords=BEGINNER_CHORDS, metronome=None):
"""Run one chord flashcard"""
global lastchord
while True:
chord = random.choice(chords)
if chord == lastchord:
continue
lastchord = chord
break
print("\n\n\nchord:")
print(bigtext(chord))
time.sleep(2)
for i in range(2):
play_chord(chord)
time.sleep(1)
display_chord(chord)
for i in range(REPEAT_PLAY):
play_chord(chord)
def note_flashcard(allow_sharps=False):
"""Run one note flashcard"""
while True:
note = random.choice(list(NOTE2STRING.keys()))
if allow_sharps or '#' not in note:
break
print("\n\n\nnote:")
print(bigtext(note))
time.sleep(3)
play_notes(note)
time.sleep(3)
display_note(note)
time.sleep(1)
for i in range(REPEAT_PLAY):
play_notes(note)
time.sleep(1)
def read_config():
"""Look for GUITARFLASH env variable or ~/.config/guitarflash/*.conf
for a list of chords to show.
Return a list of chord name strings, defaulting to BEGINNER_CHORDS.
Chords are not unique; if a chord name repeats, it will be shown more.
Suggested conf file name is $XDG_CONFIG_HOME/guitarflash/guitarflash.conf
but you can have multiple files; everything matching
$XDG_CONFIG_HOME/guitarflash/*.conf will be read.
"""
if "GUITARFLASH" in os.environ:
return os.environ["GUITARFLASH"].split()
try:
chords = []
confdir = os.path.join(xdg.BaseDirectory.xdg_config_home,
"guitarflash")
for conffile in os.listdir(confdir):
if not conffile.endswith(".conf"):
continue
with open(os.path.join(confdir, conffile)) as fp:
for line in fp:
chords += line.split()
if chords:
return chords
print("Didn't find any chords in", confdir)
except Exception as e:
print("Exception finding conffiles; showing beginner chords")
print(e)
pass
return BEGINNER_CHORDS
if __name__ == '__main__':
# test_main()
parser = argparse.ArgumentParser(description="Guitar Flashcards")
parser.add_argument('-c', "--chord_test", action="store_true",
help="Test the user on knowledge of chords")
parser.add_argument('-n', "--note_test", action="store_true",
help="Test the user on knowledge of individual notes")
parser.add_argument('-C', "--use-chords", default=None, action="store",
help="chords to use, comma or space separated "
"you can also specify them in "
"GUITARFLASH env variable or "
"XDG_CONFIG_HOME/guitarflash/*.conf")
parser.add_argument('-s', "--show-chords", default=False,
action="store_true",
help="Just print the chord charts, no flashcards")
parser.add_argument('-m', "--bpm", "--metronome",
action="store", default=0, dest="bpm", type=int,
help='Metronome Beats per Minute')
parser.add_argument('-v', "--volume",
action="store", default=1, dest="volume", type=float,
help='Volume (a decimal, 1 = full volume)')
parser.add_argument("--allow-sharps", action="store_true", default=False,
help="Include sharps in the notes to be tested")
args = parser.parse_args(sys.argv[1:])
Volume = args.volume
if not args.chord_test and not args.note_test:
parser.print_help()
sys.exit(1)
initialize()
# Get a list of chords to use, otherwise, show just beginner chords
if args.use_chords:
chords = re.split(r"\s+|,", args.use_chords)
else:
chords = read_config()
chords = sanity_check(chords)
# Just showing, no flashcard test?
if args.show_chords:
for chord in chords:
display_chord(chord)
print()
sys.exit(0)
if args.bpm:
start_metronome(args.bpm)
print(args.chord_test, args.note_test)
try:
while True:
if args.chord_test and args.note_test:
if random.randint(0, 1):
chord_flashcard(chords=chords)
else:
note_flashcard(allow_sharps=args.allow_sharps)
elif args.chord_test:
chord_flashcard(chords=chords)
elif args.note_test:
note_flashcard(allow_sharps=args.allow_sharps)
except KeyboardInterrupt:
print("Bye!")
stop_metronome()
sys.exit()