Skip to content

Commit c5aab3c

Browse files
committed
Add an example to create a MIDI file
1 parent 89a3327 commit c5aab3c

File tree

4 files changed

+39
-0
lines changed

4 files changed

+39
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
.idea/
22
venv/
3+
.DS_Store
34

45
# Byte-compiled / optimized / DLL files
56
__pycache__/

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
## Forthcoming
22

3+
- Add an example to create a MIDI file.
4+
35
## v0.5.1
46

57
- Add `m7b9b5` quality.

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,10 @@ True
108108
<Chord: E7> # V7 of A minor
109109
```
110110

111+
## Examples
112+
113+
- [pychord-midi.py](./examples/pychord-midi.py) - Create a MIDI file using PyChord and pretty_midi.
114+
111115
## Supported Python Versions
112116

113117
- 2.7

examples/pychord-midi.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# An example to create MIDI file with PyChord and pretty_midi
2+
# Prerequisite: pip install pretty_midi
3+
# pretty_midi: https://github.com/craffel/pretty-midi
4+
5+
6+
import pretty_midi
7+
8+
from pychord import Chord
9+
10+
11+
def create_midi(chords):
12+
midi_data = pretty_midi.PrettyMIDI()
13+
piano_program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano')
14+
piano = pretty_midi.Instrument(program=piano_program)
15+
length = 1
16+
for n, chord in enumerate(chords):
17+
for note_name in chord.components_with_pitch(root_pitch=4):
18+
note_number = pretty_midi.note_name_to_number(note_name)
19+
note = pretty_midi.Note(velocity=100, pitch=note_number, start=n * length, end=(n + 1) * length)
20+
piano.notes.append(note)
21+
midi_data.instruments.append(piano)
22+
midi_data.write('chord.mid')
23+
24+
25+
def main():
26+
chords_str = ["C", "Dm7", "G", "C"]
27+
chords = [Chord(c) for c in chords_str]
28+
create_midi(chords)
29+
30+
31+
if __name__ == '__main__':
32+
main()

0 commit comments

Comments
 (0)