Search code examples
pythonmidimusic21

How to make MIDI file from notes with Flute instrument in Python (music21 library)


I have some notes and what I want is create the MIDI file with Flute instrument. But what happens is that the output MIDI file plays Piano, instead of Flute. I tried other instruments, but it's always the same, Piano. What is going on?

(...)
new_note = note.Note(pattern)
new_note.offset = offset
new_note.storedInstrument = instrument.Piano()
output_notes.append(new_note)
(...)
midi_stream = stream.Stream(output_notes)
midi_stream.write('midi', fp='output.midi')

Solution

  • According to the documentation, the only class with a storedInstrument property is note.Unpitched.

    And:

    The Unpitched object does not currently do anything and should not be used.

    Anyway, the testMidiProgramChangeA/B functions in music21/midi/translate.py show how this is to be done: just add the instrument object into the Stream before the Notes that should use it:

    output_notes.append(instrument.Flute())
    new_note = ...
    output_notes.append(new_note)
    ...