Module to Read Midi Data Into Python

MIDI is an extremely pop and versatile format for music data, whether you lot're using information technology as a digital musical musical instrument interface or just transcribing music in it to bear witness your bandmates new songs. Mido is a Python library you can use to interact with MIDI in your code.

Let's walk through the basics of working with MIDI data using the Mido Python library.

Setting upward

Before moving on, you will demand to make sure you take an up to date version of Python 3 and pip installed. Brand certain you create and activate a virtual environment earlier installing Mido.

Run the post-obit command to install Mido in your virtual surroundings:

In the rest of this post, we will be working with these two MIDI files equally examples. Download them and salvage them to the directory where you want your code to run.

VampireKillerCV1.mid is the phase ane music from the original Castlevania game on the NES. VampireKillerCV3.mid is the Castlevania 3 version of the same vocal, which is slightly remixed and plays later in the game when you enter Dracula'south Castle (hence the track proper noun "Deja Vu")!

Castlevania Stairs

Working with MidiFile objects and runway data

The MidiFile object is i of the bones types you're going to work with when using Mido. As the name implies, it can be used to read, write and play back MIDI files. You can create a new MIDI file or open up an existing file as a MidiFile object. Any changes yous make to this object won't be written until you call the save() method with a filename.

Let's start by opening VampireKillerCV1.mid and examining its properties. Open upward your Python shell and follow along with this code which will create a new MidiFile object with the contents of the file we desire:

            from mido import MidiFile  mid = MidiFile('VampireKillerCV1.mid', prune=True) print(mid)                      

Nosotros are using clip=True simply in case we end upwards opening a file with notes over 127 velocity, the maximum for a notation in a MIDI file. This isn't a typical scenario and would commonly mean the data is corrupted, simply when working with large amounts of files it'southward good to keep in mind that this is a possibility. This would clip the velocity of all notes to 127 if they are higher than that.

Y'all should see some output similar to this:

<midi file 'VampireKillerCV1.mid' blazon ane, 9 tracks, 4754 messages>

This means that the MIDI file has 9 synchronous tracks, with 4754 letters inside of them. Each MidiFile has a type property that designates how the tracks interact with each other.

There are 3 types of MIDI files:

  • type 0 (single rail): all messages are saved in ane track
  • blazon i (synchronous): all tracks start at the same time
  • blazon two (asynchronous): each rail is contained of the others

Let'south loop through some of the tracks and run into what we notice:

            for track in mid.tracks:     impress(track)                      

Your output should look something like this:

            <midi runway '' 5 messages> <midi runway 'CV1- Vampire Killer' 7 messages> <midi rails 'Staff-2' 635 messages> <midi track 'Staff-3' 659 messages> <midi rail 'Staff-iv' 728 messages> <midi rails 'Staff-5' 635 messages> <midi track 'Staff-6' 659 messages> <midi runway 'Staff-7' 1421 messages> <midi track 'Staff-ane' v messages>                      

This allows you to see the track titles and how many messages are in each track. You can loop through the messages in a rail:

            for msg in mid.tracks[0]:     print(msg)                      

This particular track contains just meta information about the MIDI file in general such as the tempo and fourth dimension signature, but other tracks incorporate bodily musical information:

            <meta message time_signature numerator=iv denominator=4 clocks_per_click=24 notated_32nd_notes_per_beat=8 time=0> <meta message key_signature key='C' time=0> <meta bulletin smpte_offset frame_rate=24 hours=33 minutes=0 seconds=0 frames=0 sub_frames=0 time=0> <meta message set_tempo tempo=468750 fourth dimension=0> <meta bulletin end_of_track time=0>                      

At present permit'due south actually practice something with this info!

Manipulating MIDI tracks and writing new files

If you've opened this file in a music program such as GarageBand, yous might have noticed that there are duplicate tracks for the primary melody and harmony (corresponding to the NES foursquare wave channels 1 and ii in the source tune). This kind of thing is pretty common when dealing with video game music MIDIs, and might seem unnecessary.

Permit'due south write some code to make clean this file upward and remove the indistinguishable tracks to make it more closely resemble the original NES version. Create and open a file called remove_duplicates.py, and add the post-obit lawmaking to it:

            import os  from mido import MidiFile   cv1 = MidiFile('VampireKillerCV1.mid', clip=Truthful)  message_numbers = [] duplicates = []  for runway in cv1.tracks:     if len(track) in message_numbers:         duplicates.append(track)     else:         message_numbers.append(len(track))  for rails in duplicates:     cv1.tracks.remove(track)  cv1.save('new_song.mid')                      

This code loops through the tracks in our MIDI file, searches for tracks that have the same verbal number of messages, and removes them from the overall MIDI file to get rid of the duplicates.

The new MIDI file is saved to new_song.mid to keep the original file intact. Run the code with the post-obit command:

            python remove_duplicates.py                      

Now open up upwards new_song.mid and see for yourself that the MIDI file has no duplicate tracks!

Garage Band project with the MIDI tracks

Let's make some new music

Cleaning up MIDI files is cool, but making new music is a lot more than fun! If you open VampireKillerCV3.mid yous can hear the Castlevania three version of this song is remixed to be a little more than upbeat. The melody stays generally the same but the harmony adds some more flavor, and the bass and drums are both played at a more consistent footstep every bit opposed to the original game.

Permit'southward write some code to take the bass and pulsate tracks from the Castlevania 3 version and brew them upwards with the original melody and harmony tracks from the first Castlevania game.

Open a file called mashup.py and add together the following code to it:

            import os  from mido import MidiFile   cv1 = MidiFile('new_song.mid', prune=Truthful) cv3 = MidiFile('VampireKillerCV3.mid', clip=Truthful)  del cv1.tracks[four] del cv1.tracks[four]  cv1.tracks.append(cv3.tracks[4]) cv1.tracks.append(cv3.tracks[5])  cv1.save('mashup.mid')                      

This lawmaking deletes the bass and drum tracks from the outset file, and adds the bass and drum tracks from the second file. Notice that we are opening new_song.mid and then that nosotros have the version of the MIDI with no duplicate tracks, and saving the new tune to a file called mashup.mid.

Run this lawmaking and open mashup.mid and jam out to our new remix of Vampire Killer from Castlevania ane and 3.

At present what?

There is a lot y'all tin can do with MIDI data. You tin use it to write interfaces for digital instruments, or employ information technology to clean up data to train on a neural network with Magenta. This post only brushed the surface of the functionality of the Mido library, but I hope you lot experience a little more equipped to take this further and employ it for your own MIDI files!

Experience costless to reach out for any questions or to testify off any cool music you make with Python:

  • Email: Sagnew@twilio.com
  • Twitter: @Sagnewshreds
  • GitHub: Sagnew
  • Twitch (streaming live code): Sagnewshreds

rehfischcomplaccese.blogspot.com

Source: https://www.twilio.com/blog/working-with-midi-data-in-python-using-mido

0 Response to "Module to Read Midi Data Into Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel