mirror of
https://github.com/kennethreitz/pytheory.git
synced 2026-06-05 23:00:20 +00:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 02df87af09 | |||
| b3110c6e0e | |||
| fd82dccbfd | |||
| 6f7f9008b0 | |||
| acb92171a1 | |||
| c006f5b3da | |||
| 9da3ac8b28 | |||
| e94ef5dcfd | |||
| a5e47c37cd | |||
| 8a9651f989 | |||
| cc4a25e70d | |||
| 904c61b2d6 | |||
| d23de92713 | |||
| e8bfeb884a | |||
| 6aad427fb8 | |||
| e9c630705e | |||
| e78ba203d9 |
@@ -62,6 +62,22 @@ $ pip install pytheory
|
||||
['C major', 'G major', 'A minor', 'F major']
|
||||
```
|
||||
|
||||
## Keys and Progressions
|
||||
|
||||
```pycon
|
||||
>>> from pytheory import Key
|
||||
|
||||
>>> key = Key("G", "major")
|
||||
>>> key.chords
|
||||
['G major', 'A minor', 'B minor', 'C major', 'D major', 'E minor', 'F# diminished']
|
||||
|
||||
>>> [c.identify() for c in key.progression("I", "V", "vi", "IV")]
|
||||
['G major', 'D major', 'E minor', 'C major']
|
||||
|
||||
>>> Key.detect("C", "E", "G", "A", "D")
|
||||
<Key C major>
|
||||
```
|
||||
|
||||
## Chord Analysis
|
||||
|
||||
```pycon
|
||||
@@ -116,7 +132,10 @@ $ pip install pytheory
|
||||
>>> Fretboard.keyboard(25, "C3") # 25-key MIDI controller
|
||||
|
||||
>>> CHARTS['western']['Am'].fingering(fretboard=Fretboard.guitar())
|
||||
(0, 1, 2, 2, 0, 0)
|
||||
Fingering(e=0, B=1, G=2, D=2, A=0, E=0)
|
||||
|
||||
>>> Fretboard.guitar().fingering(0, 1, 0, 2, 3, 0).identify()
|
||||
'C major'
|
||||
```
|
||||
|
||||
## Audio Playback
|
||||
@@ -127,6 +146,22 @@ $ pip install pytheory
|
||||
>>> tone = Tone.from_string("A4", system="western")
|
||||
>>> play(tone, t=1_000) # sine wave, 1 second
|
||||
>>> play(tone, synth=Synth.SAW, t=1_000) # sawtooth wave
|
||||
|
||||
>>> from pytheory import save, Chord
|
||||
>>> save(Chord.from_name("Am7"), "am7.wav", t=2_000) # save to WAV
|
||||
```
|
||||
|
||||
## Command-Line Interface
|
||||
|
||||
```
|
||||
$ pytheory tone A4 # frequency, MIDI, overtones
|
||||
$ pytheory chord C E G # identify chord from notes
|
||||
$ pytheory key G major # explore a key
|
||||
$ pytheory scale C dorian # show a scale
|
||||
$ pytheory fingering Am --capo 2 # guitar fingering
|
||||
$ pytheory progression C major I V vi IV # build a progression
|
||||
$ pytheory detect C E G A D # detect key from notes
|
||||
$ pytheory play Am7 --synth triangle # play a chord
|
||||
```
|
||||
|
||||
## Features
|
||||
@@ -138,7 +173,7 @@ $ pip install pytheory
|
||||
- **25 instrument presets**: guitar (8 tunings), 12-string, bass, mandolin family, violin family, banjo, harp, oud, sitar, shamisen, erhu, charango, pipa, balalaika, lute, pedal steel, keyboard
|
||||
- **Pitch tools**: frequency ↔ tone conversion, MIDI ↔ tone, interval naming, circle of fifths, overtone series, transposition
|
||||
- **3 temperaments**: equal, Pythagorean, quarter-comma meantone
|
||||
- **Audio synthesis**: sine, sawtooth, and triangle wave playback
|
||||
- **Audio synthesis**: sine, sawtooth, and triangle wave playback + WAV export
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
+72
-17
@@ -127,13 +127,33 @@ Quality Intervals Example tones (from C)
|
||||
>>> chart["Cm7"].acceptable_tone_names
|
||||
('C', 'D#', 'G', 'A#') # Eb and Bb shown as sharps
|
||||
|
||||
Building Chords Manually
|
||||
-------------------------
|
||||
Building Chords
|
||||
---------------
|
||||
|
||||
Several convenience constructors make chord creation concise:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Tone, Chord
|
||||
from pytheory import Chord
|
||||
|
||||
# From note names (simplest)
|
||||
Chord.from_tones("C", "E", "G") # <Chord C major>
|
||||
Chord.from_tones("A", "C", "E") # <Chord A minor>
|
||||
|
||||
# From a chord name (uses the built-in chart)
|
||||
Chord.from_name("Am7") # <Chord A minor 7th>
|
||||
Chord.from_name("G7") # <Chord G dominant 7th>
|
||||
|
||||
# From root + semitone intervals
|
||||
Chord.from_intervals("C", 4, 7) # <Chord C major>
|
||||
Chord.from_intervals("D", 3, 7) # <Chord D minor>
|
||||
Chord.from_intervals("G", 4, 7, 10) # <Chord G dominant 7th>
|
||||
|
||||
# From MIDI note numbers
|
||||
Chord.from_midi_message(60, 64, 67) # <Chord C major>
|
||||
|
||||
# Full manual construction
|
||||
from pytheory import Tone
|
||||
c_major = Chord(tones=[
|
||||
Tone.from_string("C4", system="western"),
|
||||
Tone.from_string("E4", system="western"),
|
||||
@@ -238,6 +258,39 @@ you hear a pulsing at the **beat frequency**: ``|f1 - f2|`` Hz.
|
||||
# The slowest (most perceptible) beat
|
||||
chord.beat_pulse # 189.6 Hz
|
||||
|
||||
Transposition
|
||||
-------------
|
||||
|
||||
Shift an entire chord up or down by any number of semitones:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> Chord.from_name("C").transpose(7).identify()
|
||||
'G major'
|
||||
|
||||
>>> Chord.from_name("Am7").transpose(-2).identify()
|
||||
'G minor 7th'
|
||||
|
||||
Chord Manipulation
|
||||
------------------
|
||||
|
||||
Add or remove individual tones from a chord:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Chord, Tone
|
||||
|
||||
c_major = Chord.from_tones("C", "E", "G")
|
||||
|
||||
# Add a tone to build a seventh chord
|
||||
b4 = Tone.from_string("B4", system="western")
|
||||
cmaj7 = c_major.add_tone(b4)
|
||||
cmaj7.identify() # 'C major 7th'
|
||||
|
||||
# Remove a tone
|
||||
c_again = cmaj7.remove_tone("B")
|
||||
c_again.identify() # 'C major'
|
||||
|
||||
Chord Identification
|
||||
--------------------
|
||||
|
||||
@@ -247,23 +300,25 @@ against 17 known chord types (triads, 7ths, 9ths, sus, power chords).
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Chord, Tone
|
||||
from pytheory import Chord
|
||||
|
||||
# Build a chord and identify it
|
||||
chord = Chord([
|
||||
Tone.from_string("A4", system="western"),
|
||||
Tone.from_string("C5", system="western"),
|
||||
Tone.from_string("E5", system="western"),
|
||||
])
|
||||
chord.identify() # 'A minor'
|
||||
# From note names
|
||||
Chord.from_tones("A", "C", "E").identify() # 'A minor'
|
||||
Chord.from_tones("G", "B", "D", "F").identify() # 'G dominant 7th'
|
||||
|
||||
# Works with any voicing or inversion
|
||||
chord2 = Chord([
|
||||
Tone.from_string("E4", system="western"),
|
||||
Tone.from_string("G4", system="western"),
|
||||
Tone.from_string("C5", system="western"),
|
||||
])
|
||||
chord2.identify() # 'C major' (first inversion detected)
|
||||
Chord.from_tones("E", "G", "C").identify() # 'C major'
|
||||
|
||||
# Flats work too
|
||||
Chord.from_tones("Bb", "D", "F").identify() # 'Bb major'
|
||||
|
||||
You can also access the root and quality separately:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
chord = Chord.from_name("Am7")
|
||||
chord.root # <Tone A4>
|
||||
chord.quality # 'minor 7th'
|
||||
|
||||
Harmonic Analysis
|
||||
-----------------
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
Command-Line Interface
|
||||
======================
|
||||
|
||||
PyTheory includes a CLI for quick music theory lookups from the terminal.
|
||||
|
||||
Tone Lookup
|
||||
-----------
|
||||
|
||||
Look up any note's frequency, MIDI number, enharmonic spelling, and
|
||||
overtones::
|
||||
|
||||
$ pytheory tone A4
|
||||
Note: A4
|
||||
Frequency: 440.00 Hz (equal temperament)
|
||||
MIDI: 69
|
||||
Overtones: 440.0, 880.0, 1320.0, 1760.0, 2200.0, 2640.0
|
||||
|
||||
Compare temperaments with ``--temperament``::
|
||||
|
||||
$ pytheory tone C5 --temperament pythagorean
|
||||
Note: C5
|
||||
Frequency: 521.48 Hz (pythagorean temperament)
|
||||
Equal temp: 523.25 Hz (diff: -5.9 cents)
|
||||
|
||||
Scale Display
|
||||
-------------
|
||||
|
||||
Show any scale in any system::
|
||||
|
||||
$ pytheory scale C major
|
||||
C major: C D E F G A B C
|
||||
Intervals: C4 -2- D4 -2- E4 -1- F4 -2- G4 -2- A4 -2- B4 -1- C5
|
||||
|
||||
$ pytheory scale C dorian
|
||||
$ pytheory scale Sa bhairav --system indian
|
||||
|
||||
Chord Identification
|
||||
--------------------
|
||||
|
||||
Identify a chord from its notes::
|
||||
|
||||
$ pytheory chord C E G
|
||||
Chord: C major
|
||||
Tones: C4 E4 G4
|
||||
Intervals: [4, 3]
|
||||
Harmony: 0.5833
|
||||
Dissonance: 0.0712
|
||||
Tension: 0.00 (tritones=0)
|
||||
|
||||
$ pytheory chord G B D F
|
||||
Chord: G dominant 7th
|
||||
|
||||
Key Explorer
|
||||
------------
|
||||
|
||||
Get a complete breakdown of any key — signature, diatonic triads,
|
||||
seventh chords, relative and parallel keys::
|
||||
|
||||
$ pytheory key G major
|
||||
Key: G major
|
||||
Signature: 1 sharps, 0 flats (F#)
|
||||
Scale: G A B C D E F#
|
||||
Triads:
|
||||
I G major
|
||||
ii A minor
|
||||
iii B minor
|
||||
IV C major
|
||||
V D major
|
||||
vi E minor
|
||||
vii° F# diminished
|
||||
7th chords:
|
||||
G major 7th
|
||||
A minor 7th
|
||||
...
|
||||
Relative: <Key E minor>
|
||||
Parallel: <Key G minor>
|
||||
|
||||
Guitar Fingerings
|
||||
-----------------
|
||||
|
||||
Get tablature for any of the 144 built-in chords::
|
||||
|
||||
$ pytheory fingering Am
|
||||
Am
|
||||
E|--0--
|
||||
B|--1--
|
||||
G|--2--
|
||||
D|--2--
|
||||
A|--0--
|
||||
E|--0--
|
||||
|
||||
Use ``--capo`` to see fingerings with a capo::
|
||||
|
||||
$ pytheory fingering G --capo 2
|
||||
|
||||
Chord Progressions
|
||||
------------------
|
||||
|
||||
Build progressions from Roman numerals::
|
||||
|
||||
$ pytheory progression G major I V vi IV
|
||||
Key: G major
|
||||
Progression: I → V → vi → IV
|
||||
|
||||
I G major
|
||||
V D major
|
||||
vi E minor
|
||||
IV C major
|
||||
|
||||
Key Detection
|
||||
-------------
|
||||
|
||||
Detect the most likely key from a set of notes::
|
||||
|
||||
$ pytheory detect C E G A D
|
||||
Detected key: C major
|
||||
Scale: C D E F G A B C
|
||||
|
||||
Audio Playback
|
||||
--------------
|
||||
|
||||
Play individual notes or chords (requires PortAudio)::
|
||||
|
||||
$ pytheory play A4 # Single note
|
||||
$ pytheory play C E G # Notes as chord
|
||||
$ pytheory play Am7 # Chord by name
|
||||
$ pytheory play C E G --synth saw # Sawtooth wave
|
||||
$ pytheory play A4 --duration 2000 # 2 seconds
|
||||
$ pytheory play C E G --temperament meantone
|
||||
@@ -179,9 +179,22 @@ on any instrument. It scores each possibility by:
|
||||
fb = Fretboard.guitar()
|
||||
c = CHARTS["western"]["C"]
|
||||
|
||||
# Best single fingering
|
||||
print(c.fingering(fretboard=fb))
|
||||
# (0, 1, 0, 2, 3, 0)
|
||||
# Fingerings return a Fingering object with labeled strings
|
||||
f = c.fingering(fretboard=fb)
|
||||
print(f)
|
||||
# Fingering(e=0, B=1, G=0, D=2, A=3, E=0)
|
||||
|
||||
# Access by string name or index
|
||||
f['A'] # 3
|
||||
f[1] # 1 (B string)
|
||||
|
||||
# Identify the chord directly from a fingering
|
||||
f.identify() # 'C major'
|
||||
|
||||
# Convert to a Chord for further analysis
|
||||
chord = f.to_chord()
|
||||
chord.harmony # consonance score
|
||||
chord.intervals # [4, 3] — major triad
|
||||
|
||||
# All equally-scored fingerings
|
||||
all_c = c.fingering(fretboard=fb, multiple=True)
|
||||
@@ -190,11 +203,22 @@ on any instrument. It scores each possibility by:
|
||||
f = CHARTS["western"]["F"]
|
||||
print(f.fingering(fretboard=fb))
|
||||
|
||||
You can also go from fret positions to chord identification:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# "What chord am I playing?"
|
||||
fb = Fretboard.guitar()
|
||||
f = fb.fingering(0, 0, 0, 2, 2, 0)
|
||||
print(f) # Fingering(e=0, B=0, G=0, D=2, A=2, E=0)
|
||||
print(f.identify()) # E minor
|
||||
|
||||
Reading Fingerings
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The tuple ``(0, 1, 0, 2, 3, 0)`` reads from the highest string to the
|
||||
lowest::
|
||||
Each position is labeled with its string name. Duplicate string names
|
||||
are disambiguated — on a standard guitar, high E appears as ``e`` and
|
||||
low E as ``E``::
|
||||
|
||||
e|--0-- (open — E)
|
||||
B|--1-- (fret 1 — C)
|
||||
@@ -205,6 +229,22 @@ lowest::
|
||||
|
||||
A value of ``None`` means the string is muted (not played).
|
||||
|
||||
ASCII Tablature
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
For a more visual representation, use ``tab()``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> print(CHARTS["western"]["C"].tab(fretboard=fb))
|
||||
C
|
||||
E|--0--
|
||||
B|--1--
|
||||
G|--0--
|
||||
D|--2--
|
||||
A|--3--
|
||||
E|--0--
|
||||
|
||||
Generating Full Charts
|
||||
----------------------
|
||||
|
||||
|
||||
@@ -25,14 +25,13 @@ Playing a Chord
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Chord, Tone, play
|
||||
from pytheory import Chord, play
|
||||
|
||||
c_major = Chord(tones=[
|
||||
Tone.from_string("C4", system="western"),
|
||||
Tone.from_string("E4", system="western"),
|
||||
Tone.from_string("G4", system="western"),
|
||||
])
|
||||
play(c_major, t=2_000) # Play for 2 seconds
|
||||
# From a chord name
|
||||
play(Chord.from_name("Am7"), t=2_000)
|
||||
|
||||
# From note names
|
||||
play(Chord.from_tones("C", "E", "G"), t=2_000)
|
||||
|
||||
Waveform Types
|
||||
--------------
|
||||
|
||||
@@ -40,10 +40,14 @@ Create tones, build scales, and explore music theory:
|
||||
IV = c_major.triad(3) # F A C (F major)
|
||||
V = c_major.triad(4) # G B D (G major)
|
||||
|
||||
# Guitar chord fingerings
|
||||
# Guitar chord fingerings — labeled with string names
|
||||
fb = Fretboard.guitar()
|
||||
fingering = CHARTS["western"]["Am"].fingering(fretboard=fb)
|
||||
print(fingering) # (0, 1, 2, 2, 0, 0)
|
||||
print(fingering) # Fingering(e=0, B=1, G=2, D=2, A=0, E=0)
|
||||
|
||||
# Identify a chord from fret positions
|
||||
f = fb.fingering(0, 1, 0, 2, 3, 0)
|
||||
print(f.identify()) # C major
|
||||
|
||||
What's Included
|
||||
---------------
|
||||
@@ -54,9 +58,12 @@ What's Included
|
||||
10 maqamat, 6 Japanese pentatonic scales, blues, pentatonic,
|
||||
slendro, pelog, and more
|
||||
- **Pitch calculation** in equal, Pythagorean, and meantone temperaments
|
||||
- **Chord identification**: name any chord from its notes, intervals, or
|
||||
MIDI numbers (17 chord types recognized)
|
||||
- **Chord charts** with 144 pre-built chords (12 roots x 12 qualities)
|
||||
- **Chord analysis**: consonance scoring, Plomp-Levelt dissonance,
|
||||
beat frequency calculation
|
||||
- **Fingering generation** for guitar (8 tunings), bass, ukulele, or
|
||||
any custom fretted instrument
|
||||
beat frequency calculation, harmonic tension, voice leading
|
||||
- **Key detection** and **Roman numeral analysis** (I-IV-V-I progressions)
|
||||
- **Fingering generation** for 25 instruments with labeled string names,
|
||||
including guitar (8 tunings), bass, ukulele, mandolin, and more
|
||||
- **Audio playback** with sine, sawtooth, and triangle wave synthesis
|
||||
|
||||
+121
-14
@@ -215,6 +215,35 @@ Some of the most-used chord progressions in Western music:
|
||||
My Heart Will Go On)
|
||||
- **I–IV–vi–V** — axis of awesome (many, many pop songs)
|
||||
|
||||
The :class:`~pytheory.scales.Key` class makes working with progressions
|
||||
easy:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Key
|
||||
|
||||
key = Key("G", "major")
|
||||
|
||||
# Build a progression from Roman numerals
|
||||
chords = key.progression("I", "V", "vi", "IV")
|
||||
for c in chords:
|
||||
print(c.identify())
|
||||
# G major, D major, E minor, C major
|
||||
|
||||
# Nashville number system (same thing, with integers)
|
||||
key.nashville(1, 5, 6, 4)
|
||||
|
||||
# All diatonic triads in the key
|
||||
key.chords
|
||||
# ['G major', 'A minor', 'B minor', 'C major', ...]
|
||||
|
||||
# All diatonic seventh chords
|
||||
key.seventh_chords
|
||||
# ['G major 7th', 'A minor 7th', ...]
|
||||
|
||||
# Detect the key from a set of notes
|
||||
Key.detect("C", "E", "G", "A", "D") # <Key C major>
|
||||
|
||||
The 12-Bar Blues
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -245,23 +274,101 @@ structure. In the key of A::
|
||||
# The 12-bar blues progression
|
||||
blues_12 = [I, I, I, I, IV, IV, I, I, V, IV, I, V]
|
||||
|
||||
Parallel Major and Minor
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Key Signatures
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Two scales are **relative** if they share the same notes (C major and
|
||||
A minor). Two scales are `parallel <https://en.wikipedia.org/wiki/Parallel_key>`_ if they share the same tonic but
|
||||
have different notes (C major and C minor).
|
||||
The ``signature`` property tells you how many sharps or flats a key has:
|
||||
|
||||
Mixing parallel major and minor is a powerful compositional tool —
|
||||
borrowing chords from the parallel minor in a major key creates
|
||||
dramatic color shifts. The bVI and bVII chords (Ab and Bb in C major)
|
||||
are borrowed from C minor and appear constantly in rock and film music.
|
||||
.. code-block:: python
|
||||
|
||||
>>> Key("G", "major").signature
|
||||
{'sharps': 1, 'flats': 0, 'accidentals': ['F#']}
|
||||
|
||||
>>> Key("F", "major").signature
|
||||
{'sharps': 0, 'flats': 1, 'accidentals': ['Bb']}
|
||||
|
||||
>>> Key("C", "major").signature
|
||||
{'sharps': 0, 'flats': 0, 'accidentals': []}
|
||||
|
||||
Relative and Parallel Keys
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Two keys are **relative** if they share the same notes (C major and
|
||||
A minor). Two keys are `parallel <https://en.wikipedia.org/wiki/Parallel_key>`_ if they share the same tonic but
|
||||
have different notes (C major and C minor):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> Key("C", "major").relative
|
||||
<Key A minor>
|
||||
|
||||
>>> Key("A", "minor").relative
|
||||
<Key C major>
|
||||
|
||||
>>> Key("C", "major").parallel
|
||||
<Key C minor>
|
||||
|
||||
Borrowed Chords
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
`Modal interchange <https://en.wikipedia.org/wiki/Borrowed_chord>`_ —
|
||||
borrowing chords from the parallel key — is one of the most powerful
|
||||
tools in songwriting. The bVI and bVII chords (Ab and Bb in C major)
|
||||
are borrowed from C minor and appear constantly in rock and film music:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> Key("C", "major").borrowed_chords
|
||||
# Chords from C minor that aren't in C major
|
||||
|
||||
Secondary Dominants
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A `secondary dominant <https://en.wikipedia.org/wiki/Secondary_dominant>`_
|
||||
is the V chord *of* a non-tonic chord. It creates a momentary pull
|
||||
toward that chord, adding harmonic color:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
key = Key("C", "major")
|
||||
|
||||
# V/V — the dominant of the dominant (D7 → G)
|
||||
key.secondary_dominant(5) # D dominant 7th
|
||||
|
||||
# V/ii — the dominant of the supertonic (A7 → Dm)
|
||||
key.secondary_dominant(2) # A dominant 7th
|
||||
|
||||
Random Progressions
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Need inspiration? Generate weighted random progressions. The weights
|
||||
favor common chord functions (I and vi most likely, vii least):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
key = Key("C", "major")
|
||||
chords = key.random_progression(4) # 4 chords
|
||||
[c.identify() for c in chords]
|
||||
# e.g. ['C major', 'F major', 'A minor', 'G major']
|
||||
|
||||
All Keys
|
||||
~~~~~~~~
|
||||
|
||||
Enumerate all 24 major and minor keys:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> Key.all_keys()
|
||||
[<Key C major>, <Key C minor>, <Key C# major>, <Key C# minor>, ...]
|
||||
|
||||
Scale Transposition
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Transpose an entire scale by a number of semitones:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
c_major = TonedScale(tonic="C4")["major"]
|
||||
c_minor = TonedScale(tonic="C4")["minor"]
|
||||
|
||||
# Compare: same tonic, different notes
|
||||
c_major.note_names # ['C', 'D', 'E', 'F', 'G', 'A', 'B', 'C']
|
||||
c_minor.note_names # ['C', 'D', 'D#', 'F', 'G', 'G#', 'A#', 'C']
|
||||
d_major = c_major.transpose(2) # Up a whole step
|
||||
d_major.note_names
|
||||
# ['D', 'E', 'F#', 'G', 'A', 'B', 'C#', 'D']
|
||||
|
||||
+127
-13
@@ -44,9 +44,10 @@ Creating Tones
|
||||
|
||||
from pytheory import Tone
|
||||
|
||||
# From a string (most common)
|
||||
# From a string (most common) — sharps and flats both work
|
||||
c4 = Tone.from_string("C4")
|
||||
cs4 = Tone.from_string("C#4")
|
||||
db4 = Tone.from_string("Db4") # Same pitch as C#4
|
||||
|
||||
# Direct construction
|
||||
d = Tone(name="D", octave=3)
|
||||
@@ -54,20 +55,32 @@ Creating Tones
|
||||
# With a specific system
|
||||
a4 = Tone.from_string("A4", system="western")
|
||||
|
||||
# From a frequency (finds the nearest note)
|
||||
Tone.from_frequency(440) # <Tone A4>
|
||||
Tone.from_frequency(261.63) # <Tone C4>
|
||||
|
||||
# From a MIDI note number
|
||||
Tone.from_midi(60) # <Tone C4> (middle C)
|
||||
Tone.from_midi(69) # <Tone A4>
|
||||
|
||||
Properties
|
||||
----------
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> c4 = Tone.from_string("C4")
|
||||
>>> c4 = Tone.from_string("C4", system="western")
|
||||
>>> c4.name
|
||||
'C'
|
||||
>>> c4.octave
|
||||
4
|
||||
>>> c4.full_name
|
||||
'C4'
|
||||
>>> str(c4)
|
||||
'C4'
|
||||
>>> c4.letter # Note letter without accidentals
|
||||
'C'
|
||||
>>> c4.midi # MIDI note number
|
||||
60
|
||||
>>> c4.exists # Is this note in the system?
|
||||
True
|
||||
|
||||
Pitch and Frequency
|
||||
-------------------
|
||||
@@ -125,9 +138,47 @@ same note name:
|
||||
>>> c5.pitch(temperament="pythagorean")
|
||||
521.48 # Slightly different!
|
||||
|
||||
# Symbolic output (SymPy expression)
|
||||
Symbolic Pitch
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Pass ``symbolic=True`` to get exact pitch ratios as
|
||||
`SymPy <https://en.wikipedia.org/wiki/SymPy>`_ expressions instead of
|
||||
floating-point approximations. This is useful for mathematical analysis,
|
||||
proving tuning relationships, or comparing temperaments with exact
|
||||
arithmetic.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> a4 = Tone.from_string("A4", system="western")
|
||||
|
||||
# Equal temperament: irrational ratios (roots of 2)
|
||||
>>> a4.pitch(symbolic=True)
|
||||
440
|
||||
>>> Tone.from_string("C5", system="western").pitch(symbolic=True)
|
||||
440*2**(1/4)
|
||||
|
||||
# Pythagorean: pure rational ratios (powers of 3/2)
|
||||
>>> Tone.from_string("G4", system="western").pitch(
|
||||
... temperament="pythagorean", symbolic=True)
|
||||
660
|
||||
|
||||
# Compare the major third across temperaments
|
||||
>>> e4 = Tone.from_string("E4", system="western")
|
||||
>>> e4.pitch(temperament="equal", symbolic=True)
|
||||
440*2**(1/3)
|
||||
>>> e4.pitch(temperament="pythagorean", symbolic=True)
|
||||
12160/27
|
||||
>>> e4.pitch(temperament="meantone", symbolic=True)
|
||||
550
|
||||
|
||||
# Symbolic expressions can be evaluated to any precision
|
||||
>>> e4.pitch(symbolic=True).evalf(50)
|
||||
329.62755691286991583007431157433859631791591649985
|
||||
|
||||
The symbolic output reveals *why* temperaments differ: equal temperament
|
||||
uses irrational numbers (roots of 2), Pythagorean uses powers of 3/2
|
||||
(rational but accumulating error), and meantone tunes thirds to the
|
||||
pure 5/4 ratio (sacrificing fifths).
|
||||
|
||||
Intervals and Arithmetic
|
||||
-------------------------
|
||||
@@ -178,6 +229,58 @@ Subtracting two tones gives the semitone distance:
|
||||
>>> c5 - c4 # Octave = 12 semitones
|
||||
12
|
||||
|
||||
Naming Intervals
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
The ``interval_to`` method gives the musical name of the interval
|
||||
between two tones, including compound intervals that span more than
|
||||
one octave:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> c4.interval_to(g4)
|
||||
'perfect 5th'
|
||||
>>> c4.interval_to(c4 + 4)
|
||||
'major 3rd'
|
||||
>>> c4.interval_to(c5)
|
||||
'octave'
|
||||
|
||||
# Compound intervals (more than an octave)
|
||||
>>> c4.interval_to(c4 + 19) # Octave + perfect 5th
|
||||
'perfect 5th + 1 octave'
|
||||
|
||||
Transposition
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
The ``transpose`` method returns a new tone shifted by a number of
|
||||
semitones — equivalent to the ``+`` operator but reads more clearly
|
||||
in some contexts:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> c4.transpose(7) # Same as c4 + 7
|
||||
<Tone G4>
|
||||
>>> c4.transpose(-2) # Two semitones down
|
||||
<Tone A#3>
|
||||
|
||||
MIDI
|
||||
~~~~
|
||||
|
||||
Every tone maps to a `MIDI note number <https://en.wikipedia.org/wiki/MIDI>`_
|
||||
(0–127), the standard for communicating with synthesizers, DAWs, and
|
||||
digital instruments:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> c4.midi
|
||||
60 # Middle C
|
||||
>>> Tone.from_string("A4", system="western").midi
|
||||
69 # Concert A
|
||||
|
||||
# Round-trip: MIDI → Tone → MIDI
|
||||
>>> Tone.from_midi(60).midi
|
||||
60
|
||||
|
||||
Comparison and Sorting
|
||||
----------------------
|
||||
|
||||
@@ -248,12 +351,19 @@ D major scale is D E F# G A B C# — not D E Gb G A B Db, even though
|
||||
F#=Gb and C#=Db.
|
||||
|
||||
PyTheory uses sharps by default (following the tone list ordering), but
|
||||
tones carry their enharmonic equivalents:
|
||||
every tone knows its enharmonic spelling:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> Tone.from_tuple(("C#", "Db")).names()
|
||||
['C#', 'Db']
|
||||
>>> Tone.from_string("C#4", system="western").enharmonic
|
||||
'Db'
|
||||
|
||||
>>> Tone.from_string("A#4", system="western").enharmonic
|
||||
'Bb'
|
||||
|
||||
# Natural notes have no enharmonic
|
||||
>>> Tone.from_string("C4", system="western").enharmonic is None
|
||||
True
|
||||
|
||||
The Circle of Fifths
|
||||
--------------------
|
||||
@@ -265,11 +375,15 @@ to the starting note:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> t = Tone.from_string("C4", system="western")
|
||||
>>> for i in range(12):
|
||||
... print(t.name, end=" ")
|
||||
... t = t + 7
|
||||
C G D A E B F# C# G# D# A# F
|
||||
>>> c4 = Tone.from_string("C4", system="western")
|
||||
|
||||
# Clockwise — ascending fifths (adds sharps)
|
||||
>>> [t.name for t in c4.circle_of_fifths()]
|
||||
['C', 'G', 'D', 'A', 'E', 'B', 'F#', 'C#', 'G#', 'D#', 'A#', 'F']
|
||||
|
||||
# Counter-clockwise — ascending fourths (adds flats)
|
||||
>>> [t.name for t in c4.circle_of_fourths()]
|
||||
['C', 'F', 'A#', 'D#', 'G#', 'C#', 'F#', 'B', 'E', 'A', 'D', 'G']
|
||||
|
||||
Each step clockwise adds one sharp to the key signature; each step
|
||||
counter-clockwise (ascending by fourths = 5 semitones) adds one flat.
|
||||
|
||||
@@ -34,6 +34,7 @@ Work with tones, scales, chords, and fretboards using a clean, Pythonic API.
|
||||
guide/fretboard
|
||||
guide/systems
|
||||
guide/playback
|
||||
guide/cli
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Identify chords from notes or guitar fingerings."""
|
||||
|
||||
from pytheory import Chord, Fretboard
|
||||
|
||||
print("=== Chord Identification from Notes ===")
|
||||
print()
|
||||
|
||||
test_chords = [
|
||||
("C", "E", "G"),
|
||||
("A", "C", "E"),
|
||||
("G", "B", "D", "F"),
|
||||
("D", "F#", "A"),
|
||||
("Bb", "D", "F"),
|
||||
("E", "G#", "B"),
|
||||
("C", "Eb", "Gb"),
|
||||
("C", "G"),
|
||||
("C", "F", "G"),
|
||||
("C", "D", "G"),
|
||||
]
|
||||
|
||||
for notes in test_chords:
|
||||
chord = Chord.from_tones(*notes)
|
||||
name = chord.identify() or "Unknown"
|
||||
print(f" {', '.join(notes):20s} → {name}")
|
||||
|
||||
print()
|
||||
print("=== Chord Identification from Guitar Fingerings ===")
|
||||
print()
|
||||
|
||||
fb = Fretboard.guitar()
|
||||
|
||||
# Common guitar chord shapes
|
||||
shapes = [
|
||||
("Open C", (0, 1, 0, 2, 3, 0)),
|
||||
("Open G", (3, 0, 0, 0, 2, 3)),
|
||||
("Open D", (2, 3, 2, 0, 0, 0)),
|
||||
("Open Am", (0, 1, 2, 2, 0, 0)),
|
||||
("Open Em", (0, 0, 0, 2, 2, 0)),
|
||||
("Barre F", (1, 1, 2, 3, 3, 1)),
|
||||
("Power E5", (0, 0, 0, 0, 2, 0)),
|
||||
]
|
||||
|
||||
for label, positions in shapes:
|
||||
f = fb.fingering(*positions)
|
||||
name = f.identify() or "Unknown"
|
||||
print(f" {label:12s} {f} → {name}")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Analyze harmonic tension and resolution across chords."""
|
||||
|
||||
from pytheory import Chord
|
||||
|
||||
print("Chord Tension Analysis")
|
||||
print("=" * 70)
|
||||
print()
|
||||
print(f"{'Chord':>20s} {'Tension':>8s} {'Harmony':>8s} {'Dissonance':>11s} {'Notes'}")
|
||||
print(f"{'─' * 20} {'─' * 8} {'─' * 8} {'─' * 11} {'─' * 15}")
|
||||
|
||||
chords = [
|
||||
# Stable chords
|
||||
"C", "Am",
|
||||
# Moderate tension
|
||||
"Dm7", "Cmaj7",
|
||||
# High tension
|
||||
"G7", "Bdim",
|
||||
# Extended
|
||||
"Am7", "Cmaj9",
|
||||
]
|
||||
|
||||
for name in chords:
|
||||
chord = Chord.from_name(name)
|
||||
t = chord.tension
|
||||
tones = " ".join(tone.name for tone in chord.tones)
|
||||
print(
|
||||
f"{name:>20s} {t['score']:>8.2f} {chord.harmony:>8.4f}"
|
||||
f" {chord.dissonance:>11.4f} {tones}"
|
||||
)
|
||||
|
||||
# Show the V7 → I resolution
|
||||
print()
|
||||
print("─" * 70)
|
||||
print()
|
||||
print("The V7 → I resolution (the strongest pull in tonal music):")
|
||||
print()
|
||||
|
||||
g7 = Chord.from_name("G7")
|
||||
c = Chord.from_name("C")
|
||||
|
||||
print(f" G7 (dominant): tension={g7.tension['score']:.2f} "
|
||||
f"tritones={g7.tension['tritones']} "
|
||||
f"dominant_function={g7.tension['has_dominant_function']}")
|
||||
print(f" C (tonic): tension={c.tension['score']:.2f} "
|
||||
f"tritones={c.tension['tritones']} "
|
||||
f"dominant_function={c.tension['has_dominant_function']}")
|
||||
|
||||
print()
|
||||
print("Voice leading (G7 → C):")
|
||||
for src, dst, motion in g7.voice_leading(c):
|
||||
direction = "↑" if motion > 0 else "↓" if motion < 0 else "="
|
||||
print(f" {src.name:3s} → {dst.name:3s} ({direction} {abs(motion)} semitones)")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Visualize the circle of fifths with key signatures."""
|
||||
|
||||
from pytheory import Tone, Key
|
||||
|
||||
c = Tone.from_string("C4", system="western")
|
||||
|
||||
print("╔══════════════════════════════════════════════╗")
|
||||
print("║ THE CIRCLE OF FIFTHS ║")
|
||||
print("╠══════════════════════════════════════════════╣")
|
||||
print("║ Key Sig Accidentals ║")
|
||||
print("╠══════════════════════════════════════════════╣")
|
||||
|
||||
for tone in c.circle_of_fifths():
|
||||
key = Key(tone.name, "major")
|
||||
sig = key.signature
|
||||
relative = key.relative
|
||||
|
||||
if sig["sharps"]:
|
||||
mark = f'{sig["sharps"]}#'
|
||||
elif sig["flats"]:
|
||||
mark = f'{sig["flats"]}b'
|
||||
else:
|
||||
mark = "--"
|
||||
|
||||
accidentals = ", ".join(sig["accidentals"]) if sig["accidentals"] else "none"
|
||||
print(f"║ {tone.name:3s} {mark:3s} {accidentals:20s} rel: {relative.tonic_name} {relative.mode:5s} ║")
|
||||
|
||||
print("╚══════════════════════════════════════════════╝")
|
||||
|
||||
# Show that 12 fifths returns to the start
|
||||
print()
|
||||
print("Proof: 12 perfect fifths cycle through all 12 tones")
|
||||
names = [t.name for t in c.circle_of_fifths()]
|
||||
print(f" {' → '.join(names)} → {names[0]}")
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Explore instruments, tunings, and chord fingerings."""
|
||||
|
||||
from pytheory import Fretboard, CHARTS
|
||||
|
||||
# ── Compare Instruments ─────────────────────────────────────────────────
|
||||
|
||||
print("Instrument Tunings")
|
||||
print("=" * 55)
|
||||
|
||||
instruments = [
|
||||
("Guitar (standard)", Fretboard.guitar()),
|
||||
("Guitar (drop D)", Fretboard.guitar("drop d")),
|
||||
("Guitar (open G)", Fretboard.guitar("open g")),
|
||||
("Guitar (DADGAD)", Fretboard.guitar("dadgad")),
|
||||
("Bass", Fretboard.bass()),
|
||||
("Ukulele", Fretboard.ukulele()),
|
||||
("Mandolin", Fretboard.mandolin()),
|
||||
("Violin", Fretboard.violin()),
|
||||
("Banjo", Fretboard.banjo()),
|
||||
("Bouzouki (Irish)", Fretboard.bouzouki()),
|
||||
]
|
||||
|
||||
for name, fb in instruments:
|
||||
tuning = " ".join(t.full_name for t in fb.tones)
|
||||
print(f" {name:22s} {tuning}")
|
||||
|
||||
# ── Guitar Chord Chart ──────────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("Guitar Chord Chart (standard tuning)")
|
||||
print("=" * 55)
|
||||
|
||||
fb = Fretboard.guitar()
|
||||
chart = CHARTS["western"]
|
||||
|
||||
for chord_name in ["C", "G", "D", "Am", "Em", "F", "A", "E", "Dm", "G7", "C7", "Am7"]:
|
||||
f = chart[chord_name].fingering(fretboard=fb)
|
||||
print(f" {chord_name:5s} {f}")
|
||||
|
||||
# ── Capo Magic ──────────────────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("Capo Transposition")
|
||||
print("=" * 55)
|
||||
print(" Playing open chord shapes with a capo changes the key:")
|
||||
print()
|
||||
|
||||
open_shapes = ["C", "G", "D", "Am", "Em"]
|
||||
|
||||
for capo_fret in range(1, 6):
|
||||
fb_capo = Fretboard.guitar(capo=capo_fret)
|
||||
results = []
|
||||
for shape in open_shapes:
|
||||
f = chart[shape].fingering(fretboard=fb_capo)
|
||||
actual = f.identify() or "?"
|
||||
results.append(f"{shape}→{actual.split()[0]}")
|
||||
print(f" Capo {capo_fret}: {', '.join(results)}")
|
||||
|
||||
# ── Same Chord on Different Instruments ─────────────────────────────────
|
||||
|
||||
print()
|
||||
print("C Major on Different Instruments")
|
||||
print("=" * 55)
|
||||
|
||||
c_chord = chart["C"]
|
||||
for name, fb in [("Guitar", Fretboard.guitar()),
|
||||
("Ukulele", Fretboard.ukulele()),
|
||||
("Mandolin", Fretboard.mandolin()),
|
||||
("Banjo", Fretboard.banjo())]:
|
||||
try:
|
||||
f = c_chord.fingering(fretboard=fb)
|
||||
print(f" {name:12s} {f}")
|
||||
except Exception:
|
||||
print(f" {name:12s} (not available for this tuning)")
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Learn intervals — names, sounds, and relationships."""
|
||||
|
||||
from pytheory import Tone, Chord, Interval
|
||||
|
||||
c4 = Tone.from_string("C4", system="western")
|
||||
|
||||
# ── Interval Reference ──────────────────────────────────────────────────
|
||||
|
||||
print("Interval Reference (from C4)")
|
||||
print("=" * 70)
|
||||
print()
|
||||
print(f"{'Semitones':>10s} {'Note':>5s} {'Interval Name':>18s} {'Sound / Song'}")
|
||||
print(f"{'─' * 10} {'─' * 5} {'─' * 18} {'─' * 30}")
|
||||
|
||||
songs = {
|
||||
0: "Same note",
|
||||
1: "Jaws",
|
||||
2: "Happy Birthday",
|
||||
3: "Greensleeves",
|
||||
4: "Here Comes the Sun",
|
||||
5: "Here Comes the Bride",
|
||||
6: "The Simpsons",
|
||||
7: "Star Wars (main theme)",
|
||||
8: "Love Story",
|
||||
9: "My Bonnie Lies Over the Ocean",
|
||||
10: "Somewhere (West Side Story)",
|
||||
11: "Take On Me (chorus)",
|
||||
12: "Somewhere Over the Rainbow",
|
||||
}
|
||||
|
||||
for semitones in range(13):
|
||||
tone = c4 + semitones
|
||||
name = c4.interval_to(tone)
|
||||
song = songs.get(semitones, "")
|
||||
print(f"{semitones:>10d} {tone.name:>5s} {name:>18s} {song}")
|
||||
|
||||
# ── Interval Constants ──────────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("Interval Constants (pytheory.Interval)")
|
||||
print("=" * 40)
|
||||
|
||||
constants = [
|
||||
("UNISON", Interval.UNISON),
|
||||
("MINOR_SECOND", Interval.MINOR_SECOND),
|
||||
("MAJOR_SECOND", Interval.MAJOR_SECOND),
|
||||
("MINOR_THIRD", Interval.MINOR_THIRD),
|
||||
("MAJOR_THIRD", Interval.MAJOR_THIRD),
|
||||
("PERFECT_FOURTH", Interval.PERFECT_FOURTH),
|
||||
("TRITONE", Interval.TRITONE),
|
||||
("PERFECT_FIFTH", Interval.PERFECT_FIFTH),
|
||||
("MINOR_SIXTH", Interval.MINOR_SIXTH),
|
||||
("MAJOR_SIXTH", Interval.MAJOR_SIXTH),
|
||||
("MINOR_SEVENTH", Interval.MINOR_SEVENTH),
|
||||
("MAJOR_SEVENTH", Interval.MAJOR_SEVENTH),
|
||||
("OCTAVE", Interval.OCTAVE),
|
||||
]
|
||||
|
||||
for name, value in constants:
|
||||
print(f" Interval.{name:16s} = {value}")
|
||||
|
||||
# ── Compound Intervals ─────────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("Compound Intervals (beyond one octave)")
|
||||
print("=" * 50)
|
||||
|
||||
for semitones in [13, 14, 15, 16, 19, 24]:
|
||||
tone = c4 + semitones
|
||||
name = c4.interval_to(tone)
|
||||
print(f" {semitones:2d} semitones {tone.full_name:5s} {name}")
|
||||
|
||||
# ── Consonance Ranking ──────────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("Intervals Ranked by Consonance")
|
||||
print("=" * 50)
|
||||
|
||||
intervals = []
|
||||
for semitones in range(1, 13):
|
||||
tone = c4 + semitones
|
||||
dyad = Chord.from_tones("C", tone.name)
|
||||
name = c4.interval_to(tone)
|
||||
intervals.append((dyad.harmony, dyad.dissonance, semitones, name))
|
||||
|
||||
# Sort by harmony score (descending)
|
||||
intervals.sort(key=lambda x: x[0], reverse=True)
|
||||
|
||||
print(f"{'Rank':>5s} {'Interval':>18s} {'Harmony':>8s} {'Dissonance':>11s}")
|
||||
print(f"{'─' * 5} {'─' * 18} {'─' * 8} {'─' * 11}")
|
||||
|
||||
for rank, (harmony, dissonance, _, name) in enumerate(intervals, 1):
|
||||
print(f"{rank:>5d} {name:>18s} {harmony:>8.4f} {dissonance:>11.4f}")
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Detect the key of a melody or chord progression."""
|
||||
|
||||
from pytheory import Key, Chord
|
||||
|
||||
print("Key Detection")
|
||||
print("=" * 55)
|
||||
print()
|
||||
|
||||
# ── Detect from Melody Notes ────────────────────────────────────────────
|
||||
|
||||
melodies = [
|
||||
("Twinkle Twinkle", ["C", "G", "A", "F", "E", "D"]),
|
||||
("Happy Birthday", ["G", "A", "B", "C", "D", "F#"]),
|
||||
("Yesterday", ["F", "E", "D", "C", "Bb", "A", "G"]),
|
||||
("Minor melody", ["A", "B", "C", "D", "E", "F", "G"]),
|
||||
("Blues lick", ["E", "G", "A", "B", "D"]),
|
||||
("Chromatic fragment", ["C", "C#", "D", "D#", "E"]),
|
||||
]
|
||||
|
||||
print("Detecting key from melody notes:")
|
||||
print()
|
||||
for label, notes in melodies:
|
||||
key = Key.detect(*notes)
|
||||
print(f" {label:22s} {', '.join(notes):30s} → {key}")
|
||||
|
||||
# ── Detect from Chord Progression ──────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("Detecting key from chord tones:")
|
||||
print()
|
||||
|
||||
progressions = [
|
||||
("I-IV-V", [("C", "E", "G"), ("F", "A", "C"), ("G", "B", "D")]),
|
||||
("Pop in G", [("G", "B", "D"), ("D", "F#", "A"), ("E", "G", "B"), ("C", "E", "G")]),
|
||||
("Jazz ii-V-I", [("D", "F", "A"), ("G", "B", "D", "F"), ("C", "E", "G", "B")]),
|
||||
]
|
||||
|
||||
for label, chord_tones in progressions:
|
||||
# Collect all unique note names
|
||||
all_notes = set()
|
||||
for tones in chord_tones:
|
||||
all_notes.update(tones)
|
||||
|
||||
key = Key.detect(*all_notes)
|
||||
chord_names = [Chord.from_tones(*t).identify() for t in chord_tones]
|
||||
print(f" {label:15s} {' → '.join(chord_names):40s} → {key}")
|
||||
|
||||
# ── All 24 Keys ─────────────────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("All 24 Major and Minor Keys")
|
||||
print("=" * 55)
|
||||
print()
|
||||
|
||||
for key in Key.all_keys():
|
||||
sig = key.signature
|
||||
acc = ", ".join(sig["accidentals"]) if sig["accidentals"] else "none"
|
||||
rel = key.relative
|
||||
print(
|
||||
f" {str(key):12s} "
|
||||
f"{sig['sharps']}# {sig['flats']}b "
|
||||
f"({acc:15s}) "
|
||||
f"rel: {rel}"
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Explore a key — its chords, progressions, and relationships."""
|
||||
|
||||
from pytheory import Key
|
||||
|
||||
def explore_key(tonic, mode="major"):
|
||||
key = Key(tonic, mode)
|
||||
sig = key.signature
|
||||
acc = ", ".join(sig["accidentals"]) or "none"
|
||||
|
||||
print(f"{'=' * 60}")
|
||||
print(f" {key}")
|
||||
print(f"{'=' * 60}")
|
||||
print()
|
||||
print(f" Scale: {' '.join(key.note_names)}")
|
||||
print(f" Signature: {sig['sharps']} sharps, {sig['flats']} flats ({acc})")
|
||||
print(f" Relative: {key.relative}")
|
||||
print(f" Parallel: {key.parallel}")
|
||||
print()
|
||||
|
||||
# Diatonic triads
|
||||
print(" Diatonic Triads:")
|
||||
for chord in key.scale.harmonize():
|
||||
numeral = chord.analyze(tonic, mode) or "?"
|
||||
print(f" {numeral:6s} {chord.identify()}")
|
||||
print()
|
||||
|
||||
# Seventh chords
|
||||
print(" Seventh Chords:")
|
||||
for name in key.seventh_chords:
|
||||
print(f" {name}")
|
||||
print()
|
||||
|
||||
# Common progressions
|
||||
print(" Common Progressions:")
|
||||
progressions = {
|
||||
"Pop": ("I", "V", "vi", "IV"),
|
||||
"Blues": ("I", "IV", "V"),
|
||||
"50s": ("I", "vi", "IV", "V"),
|
||||
"Jazz": ("ii", "V", "I"),
|
||||
}
|
||||
for label, numerals in progressions.items():
|
||||
chords = key.progression(*numerals)
|
||||
names = [c.identify() for c in chords]
|
||||
print(f" {label:8s} {' → '.join(numerals):20s} {' → '.join(names)}")
|
||||
print()
|
||||
|
||||
# Borrowed chords
|
||||
borrowed = key.borrowed_chords
|
||||
if borrowed:
|
||||
print(f" Borrowed from {key.parallel}:")
|
||||
for chord in borrowed[:4]:
|
||||
print(f" {chord.identify()}")
|
||||
print()
|
||||
|
||||
|
||||
# Explore several keys
|
||||
for tonic, mode in [("C", "major"), ("G", "major"), ("A", "minor"), ("E", "major")]:
|
||||
explore_key(tonic, mode)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Convert between MIDI note numbers, frequencies, and note names."""
|
||||
|
||||
from pytheory import Tone
|
||||
|
||||
print("MIDI ↔ Note ↔ Frequency Reference")
|
||||
print("=" * 50)
|
||||
print()
|
||||
print(f"{'MIDI':>5s} {'Note':>5s} {'Freq (Hz)':>10s} {'Octave':>6s}")
|
||||
print(f"{'─' * 5} {'─' * 5} {'─' * 10} {'─' * 6}")
|
||||
|
||||
# Show all notes from C2 to C7
|
||||
for midi in range(36, 97):
|
||||
tone = Tone.from_midi(midi)
|
||||
freq = tone.frequency
|
||||
print(f"{midi:>5d} {tone.full_name:>5s} {freq:>10.2f} {tone.octave:>6d}")
|
||||
|
||||
# Useful reference points
|
||||
print()
|
||||
print("Key Reference Points:")
|
||||
print(f" Lowest piano note: A0 = MIDI {Tone.from_string('A0', system='western').midi}")
|
||||
print(f" Middle C: C4 = MIDI {Tone.from_string('C4', system='western').midi}")
|
||||
print(f" Concert A: A4 = MIDI {Tone.from_string('A4', system='western').midi}")
|
||||
print(f" Highest piano note: C8 = MIDI {Tone.from_string('C8', system='western').midi}")
|
||||
|
||||
# Round-trip demo
|
||||
print()
|
||||
print("Round-trip conversions:")
|
||||
for start in ["C4", "A4", "F#3", "Bb5"]:
|
||||
tone = Tone.from_string(start, system="western")
|
||||
midi = tone.midi
|
||||
freq = tone.frequency
|
||||
from_midi = Tone.from_midi(midi)
|
||||
from_freq = Tone.from_frequency(freq)
|
||||
print(f" {start:4s} → MIDI {midi} → {from_midi.full_name:4s} | "
|
||||
f"{start:4s} → {freq:.2f} Hz → {from_freq.full_name}")
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Explore the overtone series — nature's chord."""
|
||||
|
||||
from pytheory import Tone, Chord
|
||||
|
||||
a4 = Tone.from_string("A4", system="western")
|
||||
|
||||
print("The Overtone Series")
|
||||
print("=" * 65)
|
||||
print()
|
||||
print("When you play a note, you're actually hearing many frequencies")
|
||||
print("at once. The fundamental plus its integer multiples:")
|
||||
print()
|
||||
print(f"{'Harmonic':>9s} {'Frequency':>10s} {'Nearest Note':>13s} {'Interval from Root'}")
|
||||
print(f"{'─' * 9} {'─' * 10} {'─' * 13} {'─' * 25}")
|
||||
|
||||
overtones = a4.overtones(16)
|
||||
|
||||
for i, hz in enumerate(overtones, 1):
|
||||
nearest = Tone.from_frequency(hz)
|
||||
if i == 1:
|
||||
interval = "Fundamental"
|
||||
else:
|
||||
interval = a4.interval_to(nearest)
|
||||
print(f"{i:>9d} {hz:>10.1f} {nearest.full_name:>13s} {interval}")
|
||||
|
||||
# ── Why Chords Sound Good ───────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("Why the Major Triad Sounds 'Natural'")
|
||||
print("=" * 65)
|
||||
print()
|
||||
print("The first 6 harmonics contain: root, octave, 5th, 2nd octave, 3rd, 5th")
|
||||
print("That's a major triad! The major chord is literally embedded in physics.")
|
||||
print()
|
||||
|
||||
c4 = Tone.from_string("C4", system="western")
|
||||
harmonics = c4.overtones(6)
|
||||
harmonic_names = [Tone.from_frequency(hz).name for hz in harmonics]
|
||||
unique = []
|
||||
for n in harmonic_names:
|
||||
if n not in unique:
|
||||
unique.append(n)
|
||||
print(f" First 6 harmonics of C: {', '.join(harmonic_names)}")
|
||||
print(f" Unique pitch classes: {', '.join(unique)}")
|
||||
print(f" C major triad: C, E, G")
|
||||
print()
|
||||
|
||||
# ── Shared Overtones = Consonance ───────────────────────────────────────
|
||||
|
||||
print("Shared Overtones Between Intervals")
|
||||
print("=" * 65)
|
||||
print()
|
||||
print("The more overtones two notes share, the more consonant they sound.")
|
||||
print()
|
||||
|
||||
root = Tone.from_string("C4", system="western")
|
||||
root_overtones = set(round(h, 1) for h in root.overtones(12))
|
||||
|
||||
for semitones, label in [(7, "Perfect 5th (C→G)"),
|
||||
(4, "Major 3rd (C→E)"),
|
||||
(5, "Perfect 4th (C→F)"),
|
||||
(3, "Minor 3rd (C→Eb)"),
|
||||
(6, "Tritone (C→F#)"),
|
||||
(1, "Minor 2nd (C→C#)")]:
|
||||
other = root + semitones
|
||||
other_overtones = set(round(h, 1) for h in other.overtones(12))
|
||||
shared = root_overtones & other_overtones
|
||||
print(f" {label:25s} {len(shared):2d} shared overtones (of first 12)")
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Build and analyze chord progressions in any key."""
|
||||
|
||||
from pytheory import Key, Chord
|
||||
|
||||
def show_progression(key, numerals, label=""):
|
||||
chords = key.progression(*numerals)
|
||||
if label:
|
||||
print(f" {label}")
|
||||
print(f" Key: {key}")
|
||||
print(f" Progression: {' – '.join(numerals)}")
|
||||
print()
|
||||
for numeral, chord in zip(numerals, chords):
|
||||
t = chord.tension
|
||||
print(
|
||||
f" {numeral:6s} {chord.identify():20s} "
|
||||
f"tension={t['score']:.2f} "
|
||||
f"{'*** DOMINANT ***' if t['has_dominant_function'] else ''}"
|
||||
)
|
||||
print()
|
||||
|
||||
|
||||
# ── Famous Progressions ─────────────────────────────────────────────────
|
||||
|
||||
print("Famous Chord Progressions")
|
||||
print("=" * 65)
|
||||
print()
|
||||
|
||||
key_c = Key("C", "major")
|
||||
|
||||
show_progression(key_c, ("I", "V", "vi", "IV"),
|
||||
"The Pop Progression (Let It Be, No Woman No Cry, Someone Like You)")
|
||||
|
||||
show_progression(key_c, ("I", "vi", "IV", "V"),
|
||||
"The 50s Progression (Stand By Me, Every Breath You Take)")
|
||||
|
||||
show_progression(key_c, ("ii", "V", "I"),
|
||||
"Jazz ii–V–I (the backbone of jazz harmony)")
|
||||
|
||||
show_progression(key_c, ("I", "IV", "V", "I"),
|
||||
"The Three-Chord Trick (blues, rock, country)")
|
||||
|
||||
# ── Same Progression in Different Keys ──────────────────────────────────
|
||||
|
||||
print("─" * 65)
|
||||
print()
|
||||
print("I – V – vi – IV in every key:")
|
||||
print()
|
||||
|
||||
for tonic in ["C", "G", "D", "A", "E", "F", "Bb", "Eb"]:
|
||||
key = Key(tonic, "major")
|
||||
chords = key.progression("I", "V", "vi", "IV")
|
||||
names = [c.identify() for c in chords]
|
||||
print(f" {tonic} major: {' → '.join(names)}")
|
||||
|
||||
# ── Nashville Number System ─────────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("─" * 65)
|
||||
print()
|
||||
print("Nashville Number System:")
|
||||
print(" (Same thing as Roman numerals, but with integers)")
|
||||
print()
|
||||
|
||||
key_g = Key("G", "major")
|
||||
chords = key_g.nashville(1, 5, 6, 4)
|
||||
names = [c.identify() for c in chords]
|
||||
print(f" G major: 1 – 5 – 6 – 4 → {' → '.join(names)}")
|
||||
|
||||
# ── Random Progression Generator ────────────────────────────────────────
|
||||
|
||||
print()
|
||||
print("─" * 65)
|
||||
print()
|
||||
print("Random 8-bar progressions:")
|
||||
print()
|
||||
|
||||
for _ in range(3):
|
||||
key = Key("C", "major")
|
||||
chords = key.random_progression(8)
|
||||
names = [c.identify().split()[0] for c in chords] # Just root names
|
||||
print(f" | {' | '.join(names)} |")
|
||||
+201
-63
@@ -1,78 +1,216 @@
|
||||
from time import sleep
|
||||
"""Play melodies and chord progressions with PyTheory.
|
||||
|
||||
from pytheory import TonedScale, Tone, CHARTS, play
|
||||
Requires PortAudio: brew install portaudio (macOS)
|
||||
"""
|
||||
|
||||
from pytheory import Tone, Chord, Key, TonedScale, play, Synth
|
||||
|
||||
# ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
BPM = 180
|
||||
BEAT = 60_000 // BPM # ms per beat
|
||||
|
||||
|
||||
# Add this constant at the top of the file, after the imports
|
||||
EIGHTH_NOTE = 0.25
|
||||
QUARTER_NOTE = 0.5
|
||||
|
||||
# Add scale definition after the constants
|
||||
C_MAJOR = TonedScale(tonic="C4")
|
||||
def play_melody(notes, synth=Synth.SINE):
|
||||
"""Play a sequence of (note_string, beats) tuples."""
|
||||
try:
|
||||
for note, beats in notes:
|
||||
if note == "REST":
|
||||
import time
|
||||
time.sleep(beats * BEAT / 1000)
|
||||
else:
|
||||
tone = Tone.from_string(note, system="western")
|
||||
play(tone, synth=synth, t=int(beats * BEAT))
|
||||
except KeyboardInterrupt:
|
||||
print("\n Stopped.")
|
||||
|
||||
|
||||
def play_note(note, t=0.1):
|
||||
# Convert scale degree (1-7) to note name (0-based index)
|
||||
scale_notes = ["C4", "D4", "E4", "F4", "G4", "A4", "B4"]
|
||||
note_name = scale_notes[note - 1] # Subtract 1 because scale degrees are 1-based
|
||||
tone = Tone(note_name)
|
||||
play(tone, t=t * 1_000)
|
||||
sleep(t)
|
||||
def play_progression(chords, beats_each=2, synth=Synth.SINE):
|
||||
"""Play a list of Chord objects."""
|
||||
try:
|
||||
for chord in chords:
|
||||
name = chord.identify() or "?"
|
||||
tones = " ".join(t.full_name for t in chord.tones)
|
||||
print(f" {name:20s} {tones}")
|
||||
play(chord, synth=synth, t=int(beats_each * BEAT))
|
||||
except KeyboardInterrupt:
|
||||
print("\n Stopped.")
|
||||
|
||||
|
||||
# Twinkle Twinkle Little Star in C major
|
||||
# C C G G A A G (first line)
|
||||
# F F E E D D C (second line)
|
||||
# G G F F E E D (third line)
|
||||
# G G F F E E D (fourth line)
|
||||
# C C G G A A G (fifth line)
|
||||
# F F E E D D C (sixth line)
|
||||
# ── Songs ───────────────────────────────────────────────────────────────
|
||||
|
||||
def twinkle_twinkle():
|
||||
"""Twinkle Twinkle Little Star — C major."""
|
||||
print("Twinkle Twinkle Little Star")
|
||||
print("=" * 40)
|
||||
|
||||
def play_twinkle():
|
||||
# Define the patterns using scale degrees instead of note names
|
||||
line1 = [
|
||||
(1, EIGHTH_NOTE), # C4
|
||||
(1, EIGHTH_NOTE), # C4
|
||||
(5, EIGHTH_NOTE), # G4
|
||||
(5, EIGHTH_NOTE), # G4
|
||||
(6, EIGHTH_NOTE), # A4
|
||||
(6, EIGHTH_NOTE), # A4
|
||||
(5, QUARTER_NOTE), # G4
|
||||
]
|
||||
line2 = [
|
||||
(4, EIGHTH_NOTE), # F4
|
||||
(4, EIGHTH_NOTE), # F4
|
||||
(3, EIGHTH_NOTE), # E4
|
||||
(3, EIGHTH_NOTE), # E4
|
||||
(2, EIGHTH_NOTE), # D4
|
||||
(2, EIGHTH_NOTE), # D4
|
||||
(1, QUARTER_NOTE), # C4
|
||||
]
|
||||
line3 = [
|
||||
(5, EIGHTH_NOTE), # G4
|
||||
(5, EIGHTH_NOTE), # G4
|
||||
(4, EIGHTH_NOTE), # F4
|
||||
(4, EIGHTH_NOTE), # F4
|
||||
(3, EIGHTH_NOTE), # E4
|
||||
(3, EIGHTH_NOTE), # E4
|
||||
(2, QUARTER_NOTE), # D4
|
||||
melody = [
|
||||
# Twinkle twinkle little star
|
||||
("C4", 1), ("C4", 1), ("G4", 1), ("G4", 1),
|
||||
("A4", 1), ("A4", 1), ("G4", 2),
|
||||
# How I wonder what you are
|
||||
("F4", 1), ("F4", 1), ("E4", 1), ("E4", 1),
|
||||
("D4", 1), ("D4", 1), ("C4", 2),
|
||||
# Up above the world so high
|
||||
("G4", 1), ("G4", 1), ("F4", 1), ("F4", 1),
|
||||
("E4", 1), ("E4", 1), ("D4", 2),
|
||||
# Like a diamond in the sky
|
||||
("G4", 1), ("G4", 1), ("F4", 1), ("F4", 1),
|
||||
("E4", 1), ("E4", 1), ("D4", 2),
|
||||
# Twinkle twinkle little star
|
||||
("C4", 1), ("C4", 1), ("G4", 1), ("G4", 1),
|
||||
("A4", 1), ("A4", 1), ("G4", 2),
|
||||
# How I wonder what you are
|
||||
("F4", 1), ("F4", 1), ("E4", 1), ("E4", 1),
|
||||
("D4", 1), ("D4", 1), ("C4", 2),
|
||||
]
|
||||
|
||||
# Construct the full melody using the patterns
|
||||
melody = (
|
||||
line1 # Twinkle twinkle little star
|
||||
+ line2 # How I wonder what you are
|
||||
+ line3 # Up above the world so high
|
||||
+ line3 # Like a diamond in the sky
|
||||
+ line1 # Twinkle twinkle little star
|
||||
+ line2 # How I wonder what you are
|
||||
)
|
||||
play_melody(melody)
|
||||
|
||||
print("Playing Twinkle Twinkle Little Star...")
|
||||
for note, duration in melody:
|
||||
play_note(note, duration)
|
||||
|
||||
def ode_to_joy():
|
||||
"""Ode to Joy — Beethoven's 9th Symphony, D major."""
|
||||
print("Ode to Joy (Beethoven)")
|
||||
print("=" * 40)
|
||||
|
||||
melody = [
|
||||
# Main theme
|
||||
("F#4", 1), ("F#4", 1), ("G4", 1), ("A4", 1),
|
||||
("A4", 1), ("G4", 1), ("F#4", 1), ("E4", 1),
|
||||
("D4", 1), ("D4", 1), ("E4", 1), ("F#4", 1),
|
||||
("F#4", 1.5), ("E4", 0.5), ("E4", 2),
|
||||
# Repeat with variation
|
||||
("F#4", 1), ("F#4", 1), ("G4", 1), ("A4", 1),
|
||||
("A4", 1), ("G4", 1), ("F#4", 1), ("E4", 1),
|
||||
("D4", 1), ("D4", 1), ("E4", 1), ("F#4", 1),
|
||||
("E4", 1.5), ("D4", 0.5), ("D4", 2),
|
||||
]
|
||||
|
||||
play_melody(melody)
|
||||
|
||||
|
||||
def happy_birthday():
|
||||
"""Happy Birthday — G major."""
|
||||
print("Happy Birthday")
|
||||
print("=" * 40)
|
||||
|
||||
melody = [
|
||||
# Happy birthday to you
|
||||
("G4", 0.75), ("G4", 0.25), ("A4", 1), ("G4", 1),
|
||||
("C5", 1), ("B4", 2),
|
||||
# Happy birthday to you
|
||||
("G4", 0.75), ("G4", 0.25), ("A4", 1), ("G4", 1),
|
||||
("D5", 1), ("C5", 2),
|
||||
# Happy birthday dear [name]
|
||||
("G4", 0.75), ("G4", 0.25), ("G5", 1), ("E5", 1),
|
||||
("C5", 1), ("B4", 1), ("A4", 2),
|
||||
# Happy birthday to you
|
||||
("F5", 0.75), ("F5", 0.25), ("E5", 1), ("C5", 1),
|
||||
("D5", 1), ("C5", 2),
|
||||
]
|
||||
|
||||
play_melody(melody)
|
||||
|
||||
|
||||
def fur_elise():
|
||||
"""Fur Elise — opening bars (A minor)."""
|
||||
print("Fur Elise (opening)")
|
||||
print("=" * 40)
|
||||
|
||||
melody = [
|
||||
("E5", 0.5), ("D#5", 0.5), ("E5", 0.5), ("D#5", 0.5),
|
||||
("E5", 0.5), ("B4", 0.5), ("D5", 0.5), ("C5", 0.5),
|
||||
("A4", 1), ("REST", 0.5),
|
||||
("C4", 0.5), ("E4", 0.5), ("A4", 0.5),
|
||||
("B4", 1), ("REST", 0.5),
|
||||
("E4", 0.5), ("G#4", 0.5), ("B4", 0.5),
|
||||
("C5", 1), ("REST", 0.5),
|
||||
("E4", 0.5), ("E5", 0.5), ("D#5", 0.5),
|
||||
("E5", 0.5), ("D#5", 0.5), ("E5", 0.5), ("B4", 0.5),
|
||||
("D5", 0.5), ("C5", 0.5),
|
||||
("A4", 1),
|
||||
]
|
||||
|
||||
play_melody(melody)
|
||||
|
||||
|
||||
def pop_progression():
|
||||
"""The I–V–vi–IV pop progression in C major."""
|
||||
print("Pop Progression (I-V-vi-IV in C)")
|
||||
print("=" * 40)
|
||||
print()
|
||||
|
||||
key = Key("C", "major")
|
||||
chords = key.progression("I", "V", "vi", "IV")
|
||||
|
||||
# Play it twice
|
||||
play_progression(chords * 2)
|
||||
|
||||
|
||||
def blues_in_a():
|
||||
"""12-bar blues in A."""
|
||||
print("12-Bar Blues in A")
|
||||
print("=" * 40)
|
||||
print()
|
||||
|
||||
key = Key("A", "major")
|
||||
I = key.triad(0)
|
||||
IV = key.triad(3)
|
||||
V = key.triad(4)
|
||||
|
||||
bars = [I, I, I, I, IV, IV, I, I, V, IV, I, V]
|
||||
|
||||
play_progression(bars, beats_each=1.5)
|
||||
|
||||
|
||||
def jazz_ii_v_i():
|
||||
"""Jazz ii–V–I turnaround through several keys."""
|
||||
print("Jazz ii-V-I Turnaround")
|
||||
print("=" * 40)
|
||||
print()
|
||||
|
||||
for tonic in ["C", "F", "Bb", "Eb"]:
|
||||
key = Key(tonic, "major")
|
||||
chords = key.progression("ii", "V", "I")
|
||||
print(f" Key of {tonic}:")
|
||||
play_progression(chords, beats_each=1.5)
|
||||
print()
|
||||
|
||||
|
||||
# ── Main ────────────────────────────────────────────────────────────────
|
||||
|
||||
SONGS = {
|
||||
"1": ("Twinkle Twinkle Little Star", twinkle_twinkle),
|
||||
"2": ("Ode to Joy", ode_to_joy),
|
||||
"3": ("Happy Birthday", happy_birthday),
|
||||
"4": ("Fur Elise (opening)", fur_elise),
|
||||
"5": ("Pop Progression (I-V-vi-IV)", pop_progression),
|
||||
"6": ("12-Bar Blues in A", blues_in_a),
|
||||
"7": ("Jazz ii-V-I Turnaround", jazz_ii_v_i),
|
||||
}
|
||||
|
||||
if __name__ == "__main__":
|
||||
play_twinkle()
|
||||
try:
|
||||
print("PyTheory Song Player")
|
||||
print("=" * 40)
|
||||
print()
|
||||
|
||||
for key, (name, _) in SONGS.items():
|
||||
print(f" {key}. {name}")
|
||||
|
||||
print()
|
||||
choice = input("Pick a song (1-7, or 'all'): ").strip()
|
||||
|
||||
if choice == "all":
|
||||
for _, (_, fn) in SONGS.items():
|
||||
fn()
|
||||
print()
|
||||
elif choice in SONGS:
|
||||
SONGS[choice][1]()
|
||||
else:
|
||||
print("Playing all melodies...")
|
||||
for _, (_, fn) in SONGS.items():
|
||||
fn()
|
||||
print()
|
||||
except KeyboardInterrupt:
|
||||
print("\n\nBye!")
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Compare equal, Pythagorean, and meantone temperaments."""
|
||||
|
||||
import math
|
||||
from pytheory import Tone
|
||||
|
||||
a4 = Tone.from_string("A4", system="western")
|
||||
|
||||
print("Temperament Comparison")
|
||||
print("=" * 75)
|
||||
print()
|
||||
print(f"{'Note':>5s} {'Equal (Hz)':>12s} {'Pythag (Hz)':>12s} {'Meantone (Hz)':>14s} {'P diff':>8s} {'M diff':>8s}")
|
||||
print(f"{'─' * 5} {'─' * 12} {'─' * 12} {'─' * 14} {'─' * 8} {'─' * 8}")
|
||||
|
||||
for semitones in range(13):
|
||||
tone = a4 + semitones
|
||||
|
||||
equal = tone.pitch(temperament="equal")
|
||||
pyth = tone.pitch(temperament="pythagorean")
|
||||
mean = tone.pitch(temperament="meantone")
|
||||
|
||||
# Difference in cents (1 cent = 1/100 of a semitone)
|
||||
pyth_cents = 1200 * math.log2(pyth / equal) if pyth > 0 else 0
|
||||
mean_cents = 1200 * math.log2(mean / equal) if mean > 0 else 0
|
||||
|
||||
print(
|
||||
f"{tone.name:>5s} {equal:>12.3f} {pyth:>12.3f} {mean:>14.3f}"
|
||||
f" {pyth_cents:>+7.1f}¢ {mean_cents:>+7.1f}¢"
|
||||
)
|
||||
|
||||
print()
|
||||
print("Key intervals to listen for:")
|
||||
print()
|
||||
|
||||
intervals = [
|
||||
(4, "Major 3rd", "Meantone is pure (5:4), equal is sharp, Pythagorean sharper still"),
|
||||
(7, "Perfect 5th", "Pythagorean is pure (3:2), equal is slightly flat, meantone flatter"),
|
||||
(6, "Tritone", "The 'devil's interval' — all three temperaments handle it differently"),
|
||||
]
|
||||
|
||||
for semitones, name, note in intervals:
|
||||
tone = a4 + semitones
|
||||
equal = tone.pitch(temperament="equal")
|
||||
pyth = tone.pitch(temperament="pythagorean")
|
||||
mean = tone.pitch(temperament="meantone")
|
||||
|
||||
print(f" {name} ({a4.name}→{tone.name}):")
|
||||
print(f" Equal: {equal:.3f} Hz | Pythagorean: {pyth:.3f} Hz | Meantone: {mean:.3f} Hz")
|
||||
print(f" {note}")
|
||||
print()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Explore scales from six musical traditions around the world."""
|
||||
|
||||
from pytheory import TonedScale
|
||||
|
||||
systems = [
|
||||
("western", "C4", [
|
||||
("major", "The foundation of Western tonal music"),
|
||||
("minor", "Natural minor — dark and introspective"),
|
||||
("harmonic minor", "Raised 7th — classical, Middle Eastern flavor"),
|
||||
("dorian", "Jazz, funk, soul (So What, Scarborough Fair)"),
|
||||
("mixolydian", "Blues, rock (Norwegian Wood, Sweet Home Alabama)"),
|
||||
("phrygian", "Flamenco, metal (White Rabbit)"),
|
||||
("lydian", "Dreamy, floating (The Simpsons theme)"),
|
||||
]),
|
||||
("indian", "Sa4", [
|
||||
("bilawal", "Equivalent to Western major scale"),
|
||||
("bhairav", "Morning raga — devotional, meditative"),
|
||||
("kafi", "Equivalent to Dorian mode — romantic, earthy"),
|
||||
("bhairavi", "Equivalent to Phrygian — melancholic, devotional"),
|
||||
("kalyan", "Equivalent to Lydian — serene, uplifting"),
|
||||
]),
|
||||
("arabic", "Do4", [
|
||||
("ajam", "Equivalent to Western major scale"),
|
||||
("hijaz", "The quintessential 'Middle Eastern' sound"),
|
||||
("bayati", "Contemplative, spiritual — most common maqam"),
|
||||
("rast", "Bright, festive — the 'mother' of maqamat"),
|
||||
("nahawand", "Equivalent to Western minor — melancholic"),
|
||||
]),
|
||||
("japanese", "C4", [
|
||||
("hirajoshi", "Haunting pentatonic — koto music"),
|
||||
("miyako-bushi", "Urban folk — shamisen music"),
|
||||
("yo", "Bright pentatonic — folk songs, festival music"),
|
||||
("in", "Dark pentatonic — court music, Buddhist chant"),
|
||||
("ritsu", "Elegant pentatonic — gagaku court music"),
|
||||
]),
|
||||
("blues", "C4", [
|
||||
("blues", "The 6-note blues scale with the 'blue note'"),
|
||||
("minor pentatonic", "The backbone of rock guitar solos"),
|
||||
("major pentatonic", "Bright, open — country, folk, pop"),
|
||||
]),
|
||||
("gamelan", "C4", [
|
||||
("slendro", "5-note near-equal division — metallic, shimmering"),
|
||||
("pelog", "7-note unequal — mysterious, otherworldly"),
|
||||
]),
|
||||
]
|
||||
|
||||
for system_name, tonic, scales in systems:
|
||||
print(f"{'═' * 65}")
|
||||
print(f" {system_name.upper()}")
|
||||
print(f"{'═' * 65}")
|
||||
|
||||
ts = TonedScale(tonic=tonic, system=system_name)
|
||||
|
||||
for scale_name, description in scales:
|
||||
try:
|
||||
scale = ts[scale_name]
|
||||
notes = " ".join(scale.note_names)
|
||||
print(f" {scale_name:20s} {notes}")
|
||||
print(f" {'':20s} {description}")
|
||||
print()
|
||||
except (KeyError, IndexError):
|
||||
print(f" {scale_name:20s} (not available)")
|
||||
print()
|
||||
|
||||
print(f"{'═' * 65}")
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "pytheory"
|
||||
version = "0.4.1"
|
||||
version = "0.6.1"
|
||||
description = "Music Theory for Humans"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
"""PyTheory: Music Theory for Humans."""
|
||||
|
||||
__version__ = "0.4.1"
|
||||
__version__ = "0.6.1"
|
||||
|
||||
from .tones import Tone, Interval
|
||||
from .systems import System, SYSTEMS
|
||||
from .scales import Scale, TonedScale, Key, PROGRESSIONS
|
||||
from .chords import Chord, Fretboard, analyze_progression
|
||||
from .charts import CHARTS, charts_for_fretboard
|
||||
from .charts import CHARTS, Fingering, charts_for_fretboard
|
||||
|
||||
try:
|
||||
from .play import play, Synth
|
||||
from .play import play, save, Synth
|
||||
except OSError:
|
||||
play = None
|
||||
save = None
|
||||
Synth = None
|
||||
|
||||
# Aliases for discoverability.
|
||||
@@ -19,7 +20,7 @@ Note = Tone
|
||||
|
||||
__all__ = [
|
||||
"Tone", "Note", "Interval", "Scale", "TonedScale", "Key",
|
||||
"PROGRESSIONS", "Chord", "Fretboard", "analyze_progression",
|
||||
"PROGRESSIONS", "Chord", "Fretboard", "Fingering", "analyze_progression",
|
||||
"System", "SYSTEMS", "CHARTS", "charts_for_fretboard",
|
||||
"play", "Synth",
|
||||
"play", "save", "Synth",
|
||||
]
|
||||
|
||||
@@ -175,20 +175,6 @@ SCALES = {
|
||||
# "melodic minor": {"minor": True, "melodic": True, "hemitonic": True},
|
||||
},
|
||||
],
|
||||
# TODO: understand this
|
||||
# "hexatonic": (
|
||||
# 6,
|
||||
# {
|
||||
# # name, arguments to scale generator.
|
||||
# "wholetone": {},
|
||||
# "augmented": {},
|
||||
# "prometheus": {},
|
||||
# "blues": {},
|
||||
# },
|
||||
# ),
|
||||
# "pentatonic": (5, {}),
|
||||
# "tetratonic": (4, {}),
|
||||
# "monotonic": (1, {"monotonic": {"hemitonic": False}}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+104
-2
@@ -1,4 +1,5 @@
|
||||
import itertools
|
||||
from typing import Optional
|
||||
|
||||
from .systems import SYSTEMS
|
||||
from .tones import Tone
|
||||
@@ -6,6 +7,106 @@ from .tones import Tone
|
||||
QUALITIES = ("", "maj", "m", "5", "7", "9", "dim", "m6", "m7", "m9", "maj7", "maj9")
|
||||
MAX_FRET = 7
|
||||
|
||||
|
||||
class Fingering:
|
||||
"""A chord fingering labeled with string names.
|
||||
|
||||
Provides both index and named access to fret positions, making it
|
||||
clear which string each position corresponds to.
|
||||
|
||||
Example::
|
||||
|
||||
>>> f = Fingering(positions=(0, 3, 2, 0, 1, 0),
|
||||
... string_names=('E', 'A', 'D', 'G', 'B', 'e'))
|
||||
>>> f
|
||||
Fingering(E=0, A=3, D=2, G=0, B=1, e=0)
|
||||
>>> f['A']
|
||||
3
|
||||
>>> f[1]
|
||||
3
|
||||
"""
|
||||
|
||||
def __init__(self, positions: tuple, string_names: tuple[str, ...], *, fretboard=None) -> None:
|
||||
self.positions = tuple(positions)
|
||||
self._fretboard = fretboard
|
||||
# Disambiguate duplicate names: for standard guitar tuning
|
||||
# (high-to-low), the first occurrence of a duplicate becomes
|
||||
# lowercase (e.g. high E → 'e') while the last keeps uppercase.
|
||||
from collections import Counter
|
||||
name_counts = Counter(string_names)
|
||||
seen: dict[str, int] = {}
|
||||
unique_names: list[str] = []
|
||||
for name in string_names:
|
||||
seen[name] = seen.get(name, 0) + 1
|
||||
if name_counts[name] > 1 and seen[name] < name_counts[name]:
|
||||
unique_names.append(name.lower())
|
||||
else:
|
||||
unique_names.append(name)
|
||||
|
||||
self.string_names = tuple(unique_names)
|
||||
self._map = dict(zip(self.string_names, self.positions))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
pairs = ", ".join(
|
||||
f"{name}={'x' if pos is None else pos}"
|
||||
for name, pos in zip(self.string_names, self.positions)
|
||||
)
|
||||
return f"Fingering({pairs})"
|
||||
|
||||
def __getitem__(self, key):
|
||||
if isinstance(key, int):
|
||||
return self.positions[key]
|
||||
return self._map[key]
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.positions)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.positions)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Fingering):
|
||||
return self.positions == other.positions and self.string_names == other.string_names
|
||||
if isinstance(other, tuple):
|
||||
return self.positions == other
|
||||
return NotImplemented
|
||||
|
||||
@property
|
||||
def tones(self):
|
||||
"""Return the sounding tones for this fingering.
|
||||
|
||||
Requires that the Fingering was created with a fretboard reference.
|
||||
Muted strings (``None``) are excluded.
|
||||
"""
|
||||
if self._fretboard is None:
|
||||
raise ValueError("Cannot resolve tones without a fretboard reference.")
|
||||
tones = []
|
||||
for pos, tone in zip(self.positions, self._fretboard.tones):
|
||||
if pos is not None:
|
||||
tones.append(tone.add(pos))
|
||||
return tones
|
||||
|
||||
def to_chord(self, fretboard=None) -> "Chord":
|
||||
"""Apply this fingering to a fretboard, returning a Chord.
|
||||
|
||||
Strings with ``None`` positions (muted) are excluded.
|
||||
If no fretboard is given, uses the one stored at creation time.
|
||||
"""
|
||||
from .chords import Chord
|
||||
|
||||
fb = fretboard or self._fretboard
|
||||
if fb is None:
|
||||
raise ValueError("No fretboard provided.")
|
||||
tones = []
|
||||
for pos, tone in zip(self.positions, fb.tones):
|
||||
if pos is not None:
|
||||
tones.append(tone.add(pos))
|
||||
return Chord(tones=tones)
|
||||
|
||||
def identify(self) -> Optional[str]:
|
||||
"""Identify the chord name from this fingering."""
|
||||
return self.to_chord().identify()
|
||||
|
||||
CHARTS = {}
|
||||
CHARTS["western"] = []
|
||||
|
||||
@@ -148,11 +249,12 @@ class NamedChord:
|
||||
if fingering_score(possible_fingering) == max_score:
|
||||
yield possible_fingering
|
||||
|
||||
string_names = tuple(t.name for t in fretboard.tones)
|
||||
best_fingerings = tuple([g for g in gen()])
|
||||
if not multiple:
|
||||
return self.fix_fingering(best_fingerings[0])
|
||||
return Fingering(self.fix_fingering(best_fingerings[0]), string_names, fretboard=fretboard)
|
||||
else:
|
||||
return tuple([self.fix_fingering(f) for f in best_fingerings])
|
||||
return tuple([Fingering(self.fix_fingering(f), string_names, fretboard=fretboard) for f in best_fingerings])
|
||||
|
||||
def tab(self, *, fretboard):
|
||||
"""Render this chord as ASCII guitar tablature.
|
||||
|
||||
+15
-16
@@ -680,8 +680,8 @@ class Chord:
|
||||
"""
|
||||
return Chord(tones=[t for t in self.tones if t.name != tone_name])
|
||||
|
||||
def fingering(self, *positions: int) -> Chord:
|
||||
"""Apply fret positions to each tone, returning a new Chord.
|
||||
def fingering(self, *positions: int) -> "Fingering":
|
||||
"""Apply fret positions to each tone, returning a Fingering.
|
||||
|
||||
Each position value is added (in semitones) to the corresponding
|
||||
tone. The number of positions must match the number of tones.
|
||||
@@ -690,22 +690,21 @@ class Chord:
|
||||
*positions: One integer per tone indicating the fret offset.
|
||||
|
||||
Returns:
|
||||
A new :class:`Chord` with each tone shifted by its position.
|
||||
A :class:`Fingering` labeled with tone names.
|
||||
|
||||
Raises:
|
||||
ValueError: If the number of positions doesn't match the
|
||||
number of tones.
|
||||
"""
|
||||
from .charts import Fingering
|
||||
|
||||
if not len(positions) == len(self.tones):
|
||||
raise ValueError(
|
||||
"The number of positions must match the number of tones (strings)."
|
||||
)
|
||||
|
||||
tones = []
|
||||
for i, tone in enumerate(self.tones):
|
||||
tones.append(tone.add(positions[i]))
|
||||
|
||||
return Chord(tones=tones)
|
||||
string_names = tuple(t.name for t in self.tones)
|
||||
return Fingering(positions, string_names)
|
||||
|
||||
|
||||
class Fretboard:
|
||||
@@ -1252,8 +1251,8 @@ class Fretboard:
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def fingering(self, *positions: int) -> Chord:
|
||||
"""Apply fret positions to each string, returning a Chord.
|
||||
def fingering(self, *positions: int) -> "Fingering":
|
||||
"""Apply fret positions to each string, returning a Fingering.
|
||||
|
||||
Each position value is added (in semitones) to the corresponding
|
||||
open-string tone. The number of positions must match the number
|
||||
@@ -1263,22 +1262,22 @@ class Fretboard:
|
||||
*positions: One integer per string indicating the fret number.
|
||||
|
||||
Returns:
|
||||
A :class:`Chord` with each tone shifted by its fret position.
|
||||
A :class:`Fingering` labeled with string names. Call
|
||||
``.to_chord(fretboard)`` or use the resulting chord directly.
|
||||
|
||||
Raises:
|
||||
ValueError: If the number of positions doesn't match the
|
||||
number of strings.
|
||||
"""
|
||||
from .charts import Fingering
|
||||
|
||||
if not len(positions) == len(self.tones):
|
||||
raise ValueError(
|
||||
"The number of positions must match the number of tones (strings)."
|
||||
)
|
||||
|
||||
tones = []
|
||||
for i, tone in enumerate(self.tones):
|
||||
tones.append(tone.add(positions[i]))
|
||||
|
||||
return Chord(tones=tones)
|
||||
string_names = tuple(t.name for t in self.tones)
|
||||
return Fingering(positions, string_names, fretboard=self)
|
||||
|
||||
|
||||
def analyze_progression(chords: list[Chord], key: str = "C", mode: str = "major") -> list[str | None]:
|
||||
|
||||
@@ -91,6 +91,42 @@ def cmd_progression(args):
|
||||
print(f" {numeral:6s} {chord}")
|
||||
|
||||
|
||||
def cmd_play(args):
|
||||
from .tones import Tone
|
||||
from .chords import Chord
|
||||
from .play import play, Synth
|
||||
|
||||
synth_map = {"sine": Synth.SINE, "saw": Synth.SAW, "triangle": Synth.TRIANGLE}
|
||||
synth = synth_map[args.synth]
|
||||
duration = args.duration
|
||||
|
||||
# Try chord name first (e.g. "Am", "Cmaj7"), then fall back to individual notes.
|
||||
if len(args.notes) == 1:
|
||||
note = args.notes[0]
|
||||
# Try as chord name first (Am, G7, Cmaj7, etc.)
|
||||
try:
|
||||
target = Chord.from_name(note)
|
||||
name = target.identify() or note
|
||||
label = f"{name} ({' '.join(t.full_name for t in target.tones)})"
|
||||
except (ValueError, KeyError):
|
||||
# Fall back to single tone
|
||||
target = Tone.from_string(
|
||||
note if any(c.isdigit() for c in note) else f"{note}4",
|
||||
system="western")
|
||||
label = target.full_name
|
||||
else:
|
||||
tones = [Tone.from_string(n if any(c.isdigit() for c in n) else f"{n}4",
|
||||
system="western") for n in args.notes]
|
||||
target = Chord(tones=tones)
|
||||
name = target.identify() or "Custom"
|
||||
label = f"{name} ({' '.join(t.full_name for t in tones)})"
|
||||
|
||||
print(f" Playing: {label}")
|
||||
print(f" Synth: {args.synth}")
|
||||
print(f" Duration: {duration} ms")
|
||||
play(target, temperament=args.temperament, synth=synth, t=duration)
|
||||
|
||||
|
||||
def cmd_detect(args):
|
||||
from .scales import Key
|
||||
key = Key.detect(*args.notes)
|
||||
@@ -141,6 +177,18 @@ def main():
|
||||
p.add_argument("mode", help="Mode (e.g. major, minor)")
|
||||
p.add_argument("numerals", nargs="+", help="Roman numerals (e.g. I V vi IV)")
|
||||
|
||||
# play
|
||||
p = sub.add_parser("play", help="Play notes or chords (e.g. pytheory play C E G)")
|
||||
p.add_argument("notes", nargs="+", help="Note names, with optional octave (e.g. C4, A#3, or just C E G)")
|
||||
p.add_argument("--synth", "-s", default="sine",
|
||||
choices=["sine", "saw", "triangle"],
|
||||
help="Waveform (default: sine)")
|
||||
p.add_argument("--duration", "-d", type=int, default=1000,
|
||||
help="Duration in milliseconds (default: 1000)")
|
||||
p.add_argument("--temperament", "-t", default="equal",
|
||||
choices=["equal", "pythagorean", "meantone"],
|
||||
help="Tuning temperament (default: equal)")
|
||||
|
||||
# detect
|
||||
p = sub.add_parser("detect", help="Detect key from notes (e.g. pytheory detect C E G)")
|
||||
p.add_argument("notes", nargs="+", help="Note names")
|
||||
@@ -157,6 +205,7 @@ def main():
|
||||
"key": cmd_key,
|
||||
"fingering": cmd_fingering,
|
||||
"progression": cmd_progression,
|
||||
"play": cmd_play,
|
||||
"detect": cmd_detect,
|
||||
}
|
||||
commands[args.command](args)
|
||||
|
||||
+77
-33
@@ -5,8 +5,8 @@ import sounddevice as sd
|
||||
|
||||
from .tones import Tone
|
||||
|
||||
SAMPLE_RATE = 44_100
|
||||
SAMPLE_PEAK = 4_096
|
||||
SAMPLE_RATE = 44_100 # CD-quality sample rate (Hz)
|
||||
SAMPLE_PEAK = 4_096 # Peak amplitude for 16-bit integer samples
|
||||
|
||||
|
||||
def sine_wave(hz, peak=SAMPLE_PEAK, n_samples=SAMPLE_RATE):
|
||||
@@ -20,41 +20,33 @@ def sine_wave(hz, peak=SAMPLE_PEAK, n_samples=SAMPLE_RATE):
|
||||
return numpy.resize(onecycle, (n_samples,)).astype(numpy.int16)
|
||||
|
||||
|
||||
def sawtooth_wave(hz, peak=SAMPLE_PEAK, rising_ramp_width=1, n_samples=SAMPLE_RATE):
|
||||
"""Compute N samples of a sine wave with given frequency and peak amplitude.
|
||||
def sawtooth_wave(hz, peak=SAMPLE_PEAK, n_samples=SAMPLE_RATE):
|
||||
"""Compute N samples of a sawtooth wave with given frequency and peak amplitude.
|
||||
Defaults to one second.
|
||||
rising_ramp_width is the percentage of the ramp spend rising:
|
||||
.5 is a triangle wave with equal rising and falling times.
|
||||
"""
|
||||
t = numpy.linspace(0, 1, int(500 * 440 / hz), endpoint=False)
|
||||
wave = scipy.signal.sawtooth(2 * numpy.pi * 5 * t, width=rising_ramp_width)
|
||||
wave = numpy.resize(wave, (n_samples,))
|
||||
# Sawtooth waves sound very quiet, so multiply peak by 4.
|
||||
return peak * 6 * wave.astype(numpy.int16)
|
||||
length = SAMPLE_RATE / float(hz)
|
||||
omega = numpy.pi * 2 / length
|
||||
xvalues = numpy.arange(int(length)) * omega
|
||||
onecycle = scipy.signal.sawtooth(xvalues, width=1)
|
||||
onecycle = (peak * onecycle).astype(numpy.int16)
|
||||
return numpy.resize(onecycle, (n_samples,))
|
||||
|
||||
|
||||
def triangle_wave(hz, peak=SAMPLE_PEAK, rising_ramp_width=0.5, n_samples=SAMPLE_RATE):
|
||||
def triangle_wave(hz, peak=SAMPLE_PEAK, n_samples=SAMPLE_RATE):
|
||||
"""Compute N samples of a triangle wave with given frequency and peak amplitude.
|
||||
Defaults to one second.
|
||||
rising_ramp_width is the percentage of the ramp spend rising:
|
||||
.5 is a triangle wave with equal rising and falling times.
|
||||
"""
|
||||
hz_value = float(hz)
|
||||
num_samples = int(500 * 440 / hz_value)
|
||||
t = numpy.linspace(0, 1, num_samples, endpoint=False)
|
||||
wave = scipy.signal.sawtooth(2 * numpy.pi * 5 * t, width=rising_ramp_width)
|
||||
wave = numpy.resize(wave, (n_samples,))
|
||||
# Use same amplitude as sawtooth_wave for testing
|
||||
return peak * 6 * wave.astype(numpy.int16)
|
||||
length = SAMPLE_RATE / float(hz)
|
||||
omega = numpy.pi * 2 / length
|
||||
xvalues = numpy.arange(int(length)) * omega
|
||||
onecycle = scipy.signal.sawtooth(xvalues, width=0.5)
|
||||
onecycle = (peak * onecycle).astype(numpy.int16)
|
||||
return numpy.resize(onecycle, (n_samples,))
|
||||
|
||||
|
||||
def _play_for(sample_wave, ms):
|
||||
"""Play the given NumPy array, as a sound, for ms milliseconds."""
|
||||
|
||||
# sounddevice expects float32 samples between -1 and 1
|
||||
"""Play the given NumPy sample array through the speakers."""
|
||||
normalized_wave = sample_wave.astype(numpy.float32) / SAMPLE_PEAK
|
||||
|
||||
# Play the audio and wait
|
||||
sd.play(normalized_wave, SAMPLE_RATE)
|
||||
sd.wait()
|
||||
|
||||
@@ -65,18 +57,70 @@ class Synth(Enum):
|
||||
TRIANGLE = triangle_wave
|
||||
|
||||
|
||||
def play(tone_or_chord, temperament="equal", synth=Synth.SINE, t=1_000):
|
||||
"""Play a tone or chord."""
|
||||
def _render(tone_or_chord, temperament="equal", synth=Synth.SINE, t=1_000):
|
||||
"""Render a tone or chord to a NumPy sample array.
|
||||
|
||||
Args:
|
||||
tone_or_chord: A :class:`Tone` or :class:`Chord` to render.
|
||||
temperament: Tuning temperament (``"equal"``, ``"pythagorean"``,
|
||||
or ``"meantone"``).
|
||||
synth: Waveform type — ``Synth.SINE``, ``Synth.SAW``, or
|
||||
``Synth.TRIANGLE``.
|
||||
t: Duration in milliseconds.
|
||||
|
||||
Returns:
|
||||
A NumPy int16 array of audio samples.
|
||||
"""
|
||||
n_samples = int(SAMPLE_RATE * t / 1_000)
|
||||
|
||||
if isinstance(tone_or_chord, Tone):
|
||||
chord = [synth(tone_or_chord.pitch(temperament=temperament))]
|
||||
waves = [synth(tone_or_chord.pitch(temperament=temperament), n_samples=n_samples)]
|
||||
else:
|
||||
chord = [
|
||||
synth(tone.pitch(temperament=temperament))
|
||||
waves = [
|
||||
synth(tone.pitch(temperament=temperament), n_samples=n_samples)
|
||||
for tone in tone_or_chord.tones
|
||||
]
|
||||
|
||||
_play_for(sum(chord), ms=t)
|
||||
return sum(waves)
|
||||
|
||||
|
||||
# 69 + 12*np.log2(hz_nonneg/440.)
|
||||
def play(tone_or_chord, temperament="equal", synth=Synth.SINE, t=1_000):
|
||||
"""Play a tone or chord through the speakers.
|
||||
|
||||
Args:
|
||||
tone_or_chord: A :class:`Tone` or :class:`Chord` to play.
|
||||
temperament: Tuning temperament (``"equal"``, ``"pythagorean"``,
|
||||
or ``"meantone"``).
|
||||
synth: Waveform type — ``Synth.SINE``, ``Synth.SAW``, or
|
||||
``Synth.TRIANGLE``.
|
||||
t: Duration in milliseconds (default 1000).
|
||||
|
||||
Example::
|
||||
|
||||
>>> play(Tone.from_string("A4"), t=1_000)
|
||||
>>> play(Chord.from_name("Am7"), synth=Synth.TRIANGLE, t=2_000)
|
||||
"""
|
||||
_play_for(_render(tone_or_chord, temperament=temperament, synth=synth, t=t), ms=t)
|
||||
|
||||
|
||||
def save(tone_or_chord, path, temperament="equal", synth=Synth.SINE, t=1_000):
|
||||
"""Render a tone or chord and save it as a WAV file.
|
||||
|
||||
Args:
|
||||
tone_or_chord: A :class:`Tone` or :class:`Chord` to render.
|
||||
path: Output file path (e.g. ``"chord.wav"``).
|
||||
temperament: Tuning temperament.
|
||||
synth: Waveform type.
|
||||
t: Duration in milliseconds (default 1000).
|
||||
|
||||
Example::
|
||||
|
||||
>>> save(Chord.from_name("C"), "c_major.wav", t=2_000)
|
||||
"""
|
||||
import scipy.io.wavfile
|
||||
|
||||
samples = _render(tone_or_chord, temperament=temperament, synth=synth, t=t)
|
||||
normalized = samples.astype(numpy.float32) / SAMPLE_PEAK
|
||||
# Convert to 16-bit PCM
|
||||
pcm = (normalized * 32767).astype(numpy.int16)
|
||||
scipy.io.wavfile.write(path, SAMPLE_RATE, pcm)
|
||||
|
||||
+1
-2
@@ -236,7 +236,6 @@ class Scale:
|
||||
return [self.triad(i) for i in range(unique)]
|
||||
|
||||
def degree(self, item: Union[str, int, slice], major: Optional[bool] = None, minor: bool = False) -> Optional[Union[Tone, tuple[Tone, ...]]]:
|
||||
# TODO: cleanup degrees.
|
||||
|
||||
# Ensure that both major and minor aren't passed.
|
||||
if all((major, minor)):
|
||||
@@ -653,7 +652,7 @@ class TonedScale:
|
||||
try:
|
||||
return self._scales[scale]
|
||||
except KeyError:
|
||||
pass
|
||||
return None
|
||||
|
||||
@property
|
||||
def scales(self) -> tuple[str, ...]:
|
||||
|
||||
+10
-1
@@ -24,6 +24,16 @@ class System:
|
||||
from . import Tone
|
||||
return tuple([Tone.from_tuple(tone) for tone in self.tone_names])
|
||||
|
||||
def resolve_name(self, name: str) -> str | None:
|
||||
"""Resolve a note name (including flats) to the canonical name.
|
||||
|
||||
Returns the primary name if found, or None if not recognized.
|
||||
"""
|
||||
for names in self.tone_names:
|
||||
if name in names:
|
||||
return names[0]
|
||||
return None
|
||||
|
||||
|
||||
@property
|
||||
def scales(self):
|
||||
@@ -105,7 +115,6 @@ class System:
|
||||
yield step
|
||||
else:
|
||||
for i in range(tones):
|
||||
# TODO: figure out how to make this work with monotonic.
|
||||
yield 1
|
||||
|
||||
scale = [
|
||||
|
||||
+9
-3
@@ -71,7 +71,7 @@ class Tone:
|
||||
@property
|
||||
def exists(self) -> bool:
|
||||
"""True if this tone's name is found in the associated system."""
|
||||
return self.name in self.system.tones
|
||||
return self.system.resolve_name(self.name) is not None
|
||||
|
||||
@property
|
||||
def system(self) -> object:
|
||||
@@ -331,11 +331,17 @@ class Tone:
|
||||
def _index(self) -> int:
|
||||
"""The index of this tone within its associated system's tone list.
|
||||
|
||||
Resolves enharmonic names (e.g. 'Db' → 'C#') before lookup.
|
||||
|
||||
Raises:
|
||||
ValueError: If no system is associated with this tone.
|
||||
ValueError: If no system is associated with this tone or
|
||||
the name is not found.
|
||||
"""
|
||||
try:
|
||||
return self.system.tones.index(self.name)
|
||||
canonical = self.system.resolve_name(self.name)
|
||||
if canonical is None:
|
||||
raise ValueError(f"Tone {self.name!r} not found in system")
|
||||
return self.system.tones.index(canonical)
|
||||
except AttributeError:
|
||||
raise ValueError("Tone index cannot be referenced without a system!")
|
||||
|
||||
|
||||
+226
-1
@@ -2622,7 +2622,7 @@ def test_tension_empty():
|
||||
|
||||
def test_version():
|
||||
import pytheory
|
||||
assert pytheory.__version__ == "0.4.1"
|
||||
assert pytheory.__version__ == "0.6.1"
|
||||
|
||||
|
||||
def test_all_exports():
|
||||
@@ -3647,3 +3647,228 @@ def test_charts_muted_string():
|
||||
nc = NamedChord(tone_name="C", quality="")
|
||||
fixed = nc.fix_fingering((0, -1, 2))
|
||||
assert fixed == (0, None, 2)
|
||||
|
||||
|
||||
# ── Flat note support ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_flat_tone_from_string():
|
||||
db = Tone.from_string("Db4", system="western")
|
||||
assert db.name == "Db"
|
||||
assert db.octave == 4
|
||||
|
||||
|
||||
def test_flat_tone_frequency_matches_sharp():
|
||||
db = Tone.from_string("Db4", system="western")
|
||||
cs = Tone.from_string("C#4", system="western")
|
||||
assert db.frequency == cs.frequency
|
||||
|
||||
|
||||
def test_flat_tone_frequency_all_enharmonics():
|
||||
pairs = [("Bb3", "A#3"), ("Eb4", "D#4"), ("Gb4", "F#4"), ("Ab4", "G#4")]
|
||||
for flat, sharp in pairs:
|
||||
f = Tone.from_string(flat, system="western").frequency
|
||||
s = Tone.from_string(sharp, system="western").frequency
|
||||
assert f == s, f"{flat} != {sharp}"
|
||||
|
||||
|
||||
def test_flat_tone_arithmetic():
|
||||
db = Tone.from_string("Db4", system="western")
|
||||
result = db + 2
|
||||
assert result.name == "D#"
|
||||
assert result.octave == 4
|
||||
|
||||
|
||||
def test_flat_tone_interval():
|
||||
c4 = Tone.from_string("C4", system="western")
|
||||
db4 = Tone.from_string("Db4", system="western")
|
||||
assert db4 - c4 == 1
|
||||
|
||||
|
||||
def test_flat_tone_exists():
|
||||
db = Tone.from_string("Db4", system="western")
|
||||
assert db.exists is True
|
||||
|
||||
|
||||
def test_flat_tone_index_resolves():
|
||||
db = Tone.from_string("Db4", system="western")
|
||||
cs = Tone.from_string("C#4", system="western")
|
||||
assert db._index == cs._index
|
||||
|
||||
|
||||
def test_flat_chord_from_tones():
|
||||
chord = Chord.from_tones("Db", "F", "Ab")
|
||||
assert chord.identify() == "Db major"
|
||||
|
||||
|
||||
def test_flat_chord_from_tones_minor():
|
||||
chord = Chord.from_tones("Bb", "Db", "F")
|
||||
assert chord.identify() == "Bb minor"
|
||||
|
||||
|
||||
def test_flat_chord_from_tones_seventh():
|
||||
chord = Chord.from_tones("Eb", "G", "Bb", "Db")
|
||||
assert chord.identify() == "Eb dominant 7th"
|
||||
|
||||
|
||||
def test_system_resolve_name_sharp():
|
||||
assert SYSTEMS["western"].resolve_name("C#") == "C#"
|
||||
|
||||
|
||||
def test_system_resolve_name_flat():
|
||||
assert SYSTEMS["western"].resolve_name("Db") == "C#"
|
||||
|
||||
|
||||
def test_system_resolve_name_natural():
|
||||
assert SYSTEMS["western"].resolve_name("C") == "C"
|
||||
|
||||
|
||||
def test_system_resolve_name_unknown():
|
||||
assert SYSTEMS["western"].resolve_name("X") is None
|
||||
|
||||
|
||||
# ── CLI tests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_cli_tone(capsys):
|
||||
from pytheory.cli import cmd_tone
|
||||
import argparse
|
||||
args = argparse.Namespace(note="A4", temperament="equal")
|
||||
cmd_tone(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "440.00" in out
|
||||
assert "A4" in out
|
||||
assert "MIDI" in out
|
||||
|
||||
|
||||
def test_cli_tone_pythagorean(capsys):
|
||||
from pytheory.cli import cmd_tone
|
||||
import argparse
|
||||
args = argparse.Namespace(note="C5", temperament="pythagorean")
|
||||
cmd_tone(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "Equal temp" in out
|
||||
assert "cents" in out
|
||||
|
||||
|
||||
def test_cli_scale(capsys):
|
||||
from pytheory.cli import cmd_scale
|
||||
import argparse
|
||||
args = argparse.Namespace(tonic="C", mode="major", system="western")
|
||||
cmd_scale(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "C D E F G A B C" in out
|
||||
|
||||
|
||||
def test_cli_chord(capsys):
|
||||
from pytheory.cli import cmd_chord
|
||||
import argparse
|
||||
args = argparse.Namespace(notes=["C", "E", "G"])
|
||||
cmd_chord(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "C major" in out
|
||||
assert "Harmony" in out
|
||||
assert "Tension" in out
|
||||
|
||||
|
||||
def test_cli_key(capsys):
|
||||
from pytheory.cli import cmd_key
|
||||
import argparse
|
||||
args = argparse.Namespace(tonic="G", mode="major")
|
||||
cmd_key(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "G major" in out
|
||||
assert "Signature" in out
|
||||
assert "Relative" in out
|
||||
|
||||
|
||||
def test_cli_fingering(capsys):
|
||||
from pytheory.cli import cmd_fingering
|
||||
import argparse
|
||||
args = argparse.Namespace(chord="Am", capo=0)
|
||||
cmd_fingering(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "Am" in out
|
||||
assert "|--" in out
|
||||
|
||||
|
||||
def test_cli_progression(capsys):
|
||||
from pytheory.cli import cmd_progression
|
||||
import argparse
|
||||
args = argparse.Namespace(tonic="C", mode="major", numerals=["I", "V", "vi", "IV"])
|
||||
cmd_progression(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "C major" in out
|
||||
assert "I → V → vi → IV" in out
|
||||
|
||||
|
||||
def test_cli_detect(capsys):
|
||||
from pytheory.cli import cmd_detect
|
||||
import argparse
|
||||
args = argparse.Namespace(notes=["C", "E", "G", "A", "D"])
|
||||
cmd_detect(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "C major" in out
|
||||
|
||||
|
||||
def test_cli_detect_no_match(capsys):
|
||||
from pytheory.cli import cmd_detect
|
||||
import argparse
|
||||
args = argparse.Namespace(notes=[])
|
||||
cmd_detect(args)
|
||||
out = capsys.readouterr().out
|
||||
assert "Could not detect" in out
|
||||
|
||||
|
||||
def test_cli_main_no_args(capsys):
|
||||
from pytheory.cli import main
|
||||
import sys
|
||||
old_argv = sys.argv
|
||||
sys.argv = ["pytheory"]
|
||||
try:
|
||||
main()
|
||||
except SystemExit:
|
||||
pass
|
||||
sys.argv = old_argv
|
||||
|
||||
|
||||
# ── Play module tests ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_play_render():
|
||||
"""_render produces a numpy array of the right length."""
|
||||
from pytheory.play import _render, Synth, SAMPLE_RATE
|
||||
tone = Tone.from_string("A4", system="western")
|
||||
samples = _render(tone, synth=Synth.SINE, t=500)
|
||||
expected = int(SAMPLE_RATE * 500 / 1000)
|
||||
assert len(samples) == expected
|
||||
|
||||
|
||||
def test_play_render_chord():
|
||||
from pytheory.play import _render, Synth
|
||||
chord = Chord.from_tones("C", "E", "G")
|
||||
samples = _render(chord, synth=Synth.SINE, t=200)
|
||||
assert len(samples) > 0
|
||||
|
||||
|
||||
def test_play_render_all_synths():
|
||||
from pytheory.play import _render, Synth
|
||||
tone = Tone.from_string("C4", system="western")
|
||||
for synth in Synth:
|
||||
samples = _render(tone, synth=synth, t=100)
|
||||
assert len(samples) > 0
|
||||
|
||||
|
||||
def test_play_save(tmp_path):
|
||||
"""save() writes a valid WAV file."""
|
||||
from pytheory.play import save, Synth
|
||||
path = tmp_path / "test.wav"
|
||||
tone = Tone.from_string("A4", system="western")
|
||||
save(tone, str(path), synth=Synth.SINE, t=200)
|
||||
assert path.exists()
|
||||
assert path.stat().st_size > 44 # WAV header is 44 bytes
|
||||
|
||||
|
||||
def test_play_save_chord(tmp_path):
|
||||
from pytheory.play import save
|
||||
path = tmp_path / "chord.wav"
|
||||
chord = Chord.from_tones("C", "E", "G")
|
||||
save(chord, str(path), t=200)
|
||||
assert path.exists()
|
||||
|
||||
Reference in New Issue
Block a user