[18a0552] | 1 | #! /usr/bin/env python |
---|
| 2 | |
---|
[5caf474] | 3 | def get_keyboard_edges(firstnote = 21, lastnote = 108): |
---|
[03f27b0] | 4 | octaves = 10 |
---|
[18a0552] | 5 | |
---|
[03f27b0] | 6 | # build template of white notes |
---|
| 7 | scalew = 12/7. |
---|
| 8 | xw_temp = [i*scalew for i in range(0,7)] |
---|
| 9 | # build template of black notes |
---|
| 10 | scaleb = 6/7. |
---|
| 11 | xb_temp = [i*scaleb for i in [1,3,7,9,11]] |
---|
[18a0552] | 12 | |
---|
[03f27b0] | 13 | xb,xw = [],[] |
---|
| 14 | for octave in range(octaves-1): |
---|
| 15 | for i in xb_temp: |
---|
| 16 | curnote = i+12*octave |
---|
| 17 | if curnote > firstnote-1 and curnote < lastnote+1: |
---|
| 18 | xb = xb + [curnote] |
---|
| 19 | for octave in range(octaves-1): |
---|
| 20 | for i in xw_temp: |
---|
| 21 | curnote = i+12*octave |
---|
| 22 | if curnote > firstnote-1 and curnote < lastnote+1: |
---|
| 23 | xw = xw + [curnote] |
---|
[18a0552] | 24 | |
---|
[5caf474] | 25 | return xb, xw, 2/3. *scaleb, 1/2. * scalew |
---|
[18a0552] | 26 | |
---|
| 27 | def create_keyboard_patches(firstnote, lastnote, ax = None): |
---|
| 28 | import matplotlib.pyplot as plt |
---|
| 29 | from matplotlib.path import Path |
---|
| 30 | import matplotlib.patches as mpatches |
---|
| 31 | |
---|
| 32 | blacks, whites, b_width, w_width = get_keyboard_edges(firstnote, lastnote) |
---|
| 33 | |
---|
| 34 | if not ax: |
---|
| 35 | fig = plt.figure() |
---|
| 36 | ax = fig.add_subplot(111) |
---|
| 37 | |
---|
| 38 | verts, codes = [], [] |
---|
| 39 | for white in whites: |
---|
| 40 | verts += [ (white - w_width, 0), (white - w_width, 1), (white + w_width, 1), (white + w_width, 0) ] |
---|
| 41 | verts += [ (white - w_width, 0) ] |
---|
| 42 | codes += [Path.MOVETO] + [Path.LINETO] * 4 |
---|
| 43 | path = Path(verts, codes) |
---|
| 44 | patch = mpatches.PathPatch(path, facecolor= 'white', edgecolor='black', lw=1) |
---|
| 45 | ax.add_patch(patch) |
---|
| 46 | |
---|
| 47 | verts, codes = [], [] |
---|
| 48 | for black in blacks: |
---|
| 49 | verts += [ (black - b_width, 0.33), (black - b_width, 1), (black + b_width, 1), (black + b_width, 0.33) ] |
---|
| 50 | verts += [ (black - b_width, 0.33) ] |
---|
| 51 | codes += [Path.MOVETO] + [Path.LINETO] * 4 |
---|
| 52 | path = Path(verts, codes) |
---|
| 53 | patch = mpatches.PathPatch(path, facecolor= 'black', edgecolor='black', lw=1) |
---|
| 54 | ax.add_patch(patch) |
---|
| 55 | |
---|
| 56 | ax.axis(xmin = firstnote, xmax = lastnote) |
---|
| 57 | |
---|
| 58 | if __name__ == '__main__': |
---|
| 59 | |
---|
[5caf474] | 60 | import matplotlib.pyplot as plt |
---|
| 61 | create_keyboard_patches(firstnote = 58, lastnote = 84) |
---|
| 62 | plt.show() |
---|