How to use the mido.MidiFile function in mido

To help you get started, we’ve selected a few mido examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gabelev / machine_music / parsers / hex_to_midi.py View on Github external
def convert_hex_file_with_time(infile, outfile):
    midi_file = mido.MidiFile()
    track = mido.MidiTrack()
    midi_file.tracks.append(track)
    line_num = 0
    errors = 0

    for line in infile:
        line_num += 1
        try:
            hex_str = line.rstrip("\n").split(",")
            msg = (mido.Message.from_hex(hex_str[0]))
            if len(hex_str) > 1:
                msg.time = int(float(hex_str[1]) * 1000)
            track.append(msg)
        except ValueError:
            # We don't want to stop when our ML algo makes nonsense
            errors += 1
github deep-art-project / Music / c-rnn-gan / data.py View on Github external
def _read_midi(self, filepath):
        if os.path.exists(filepath) is False:
            raise ("Midi file doesn't exist!")
        splited_filepath = filepath.split('/')
        genre, composer = splited_filepath[-3], splited_filepath[-2]
        mid = MidiFile(filepath)
        ticks_per_quarter_note = mid.ticks_per_beat
        input_ticks_per_output_tick = \
            ticks_per_quarter_note / self.output_ticks_per_quarter_note
        # Initialization finished
        # Start converting mid to song data form

        # When converting, remember to ensure the resolution of song data
        # equal to self.output_ticks_per_quarter_note
        song_data = []
        for track in mid.tracks:
            last_event_input_tick = 0
            not_closed_events = []
            for msg in track:
                if (msg.type == 'note_off') or \
                   (msg.type == 'note_on' and msg.velocity == 0):
                    retained_not_closed_events = []
github Empyrrhus / MIDI-To-Shawzin / midiToShawzin.py View on Github external
from conversion import scrubName
from conversion import identifyTime

maxNotes = 1666
maxLength = 256
defaultTicksPerBeat = 200
defaultTempo = 800000

#read midi file from command line or input
midname = ""
mid = ""
if(len(sys.argv) == 1):
	print("To convert a MIDI, drag the MIDI file onto this executable, add a MIDI file as a command line argument, or enter the MIDI filepath below.")
	midname = input()
	try:
		mid = MidiFile(midname)
	except FileNotFoundError:
		sys.exit()
else:
	try:
		midname = sys.argv[1]
		mid = MidiFile(sys.argv[1])
	except FileNotFoundError:
		print("Please enter a valid MIDI file as an argument.")
		sys.exit()

#get song scale from user
print("\nEnter the song's musical scale.\nYou can use a tool such as scales-chords.com/scalefinder.php.\nIf you have problems getting your MIDI into scale, use Chromatic.\n")
print("Scales:\n  1. Pentatonic Minor\n  2. Pentatonic Major\n  3. Chromatic\n  4. Hexatonic\n  5. Major\n  6. Minor\n  7. Hirajoshi\n  8. Phrygian\n  9. Yo\n\nEnter Scale:")
scale = 0
while True:
	scale = input()
github vipul-sharma20 / tayuya / tayuya / midi.py View on Github external
def __init__(self, file_path: str, track=0):
        self.midi_file = MidiFile(file_path)

        self.track = track
        self.midi_data = self.midi_file.tracks[track]

        # Get time signature
        ts_meta = list(filter(lambda x: x.type == constants.TIME_SIGNATURE,
                              self.midi_data))
        if ts_meta:
            numerator = ts_meta[0].numerator
            denominator = ts_meta[0].denominator
        else:
            numerator = denominator = 4
        self.time_signature = (numerator, denominator)

        self.stream = stream.Stream()
github pygametoys / pygame-pal / pgpal / music.py View on Github external
def load(self, index):
        if os.path.exists(os.path.join(config['game_path'], 'Musics')):
            try:
                name = open('./Musics/%.3d.mid' % index, 'rb')
                self.midifile = mido.MidiFile(file=name)
                return True
            except (FileNotFoundError, ValueError):
                self.midifile = mido.MidiFile()
                return False
        elif os.path.exists(os.path.join(config['game_path'], 'midi.mkf')):
            data = MKFDecoder('midi.mkf', yj1=False).read(index, True)
            if len(data):
                name = BytesIO(data)
                self.midifile = mido.MidiFile(file=name)
                return True
            else:
                self.midifile = mido.MidiFile()
                return False
        else:
            self.midifile = mido.MidiFile()
            return False
github YoongiKim / pytorch-music-composer / modules / midi.py View on Github external
def samples_to_midi(samples, file, ticks_per_beat=48, thresh=0.5):
        mid = MidiFile()
        track = MidiTrack()
        mid.tracks.append(track)

        track.append(Message('program_change', program=4))

        mid.ticks_per_beat = ticks_per_beat
        ticks_per_measure = 4 * ticks_per_beat
        ticks_per_sample = ticks_per_measure / samples_per_measure

        # note_on channel=1 note=44 velocity=127 time=816
        # note_off channel=1 note=44 velocity=64 time=24

        abs_time = 0
        last_time = 0
        for sample in samples:
            for y in range(sample.shape[0]):
github flarn2006 / BHSTools / bsl / music / midiconv.py View on Github external
#!/usr/bin/python3
import mido
import sys

notes = set()
curnote = None

mf = mido.MidiFile(sys.argv[1])

timesofar = 0

def freq(n):
	if n is None:
		return 0
	else:
		return int(2**((n-69)/12) * 440)

for msg in mf:
	time = msg.time + timesofar
	timesofar += msg.time

	if msg.type == 'note_off':
		isreallyoff = True
	else:
github gabelev / machine_music / parsers / midi_to_hex.py View on Github external
def parse_single_midi_file_with_time(infile, outfile):
    for msg in MidiFile(infile):
        if msg.time != 0:
            outfile.write(str(msg.hex()) + "," + str(msg.time) + '\n')
        else:
            outfile.write(str(msg.hex()) + '\n')
    outfile.write("\n")
github gabelev / machine_music / parsers / midi_to_hex_dir.py View on Github external
def parse_single_midi_file_with_time(infile, outfile):
    try:
        for msg in MidiFile(infile):
            if msg.time != 0:
                outfile.write(str(msg.hex()) + "," + str(msg.time) + '\n')
            else:
                outfile.write(str(msg.hex()) + '\n')
        outfile.write("\n")
    except IOError as e:
        print(e.message)
        pass