From c5aab3c4ff6ba4e1126b1dab2df4e472e1d8c68d Mon Sep 17 00:00:00 2001 From: Yuma Mihira Date: Mon, 4 Jan 2021 12:53:48 +0900 Subject: [PATCH] Add an example to create a MIDI file --- .gitignore | 1 + CHANGELOG.md | 2 ++ README.md | 4 ++++ examples/pychord-midi.py | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 39 insertions(+) create mode 100644 examples/pychord-midi.py diff --git a/.gitignore b/.gitignore index cba47f0..bef1c4e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .idea/ venv/ +.DS_Store # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 396c54e..2480dd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## Forthcoming +- Add an example to create a MIDI file. + ## v0.5.1 - Add `m7b9b5` quality. diff --git a/README.md b/README.md index 1457151..3b67997 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,10 @@ True # V7 of A minor ``` +## Examples + +- [pychord-midi.py](./examples/pychord-midi.py) - Create a MIDI file using PyChord and pretty_midi. + ## Supported Python Versions - 2.7 diff --git a/examples/pychord-midi.py b/examples/pychord-midi.py new file mode 100644 index 0000000..ba319f3 --- /dev/null +++ b/examples/pychord-midi.py @@ -0,0 +1,32 @@ +# An example to create MIDI file with PyChord and pretty_midi +# Prerequisite: pip install pretty_midi +# pretty_midi: https://github.com/craffel/pretty-midi + + +import pretty_midi + +from pychord import Chord + + +def create_midi(chords): + midi_data = pretty_midi.PrettyMIDI() + piano_program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano') + piano = pretty_midi.Instrument(program=piano_program) + length = 1 + for n, chord in enumerate(chords): + for note_name in chord.components_with_pitch(root_pitch=4): + note_number = pretty_midi.note_name_to_number(note_name) + note = pretty_midi.Note(velocity=100, pitch=note_number, start=n * length, end=(n + 1) * length) + piano.notes.append(note) + midi_data.instruments.append(piano) + midi_data.write('chord.mid') + + +def main(): + chords_str = ["C", "Dm7", "G", "C"] + chords = [Chord(c) for c in chords_str] + create_midi(chords) + + +if __name__ == '__main__': + main()