示例#1
0
    def test_midifile_to_from_file(self):
        """Write MidiFile to external file, read file back in as a MidiFile,
        `save` it to another BytesIO; compare to `self.bio`.
        Also check that writes to, reads from external file close file when
        use of them is finished.
        """
        midifile = MidiFile(file=self.bio)

        # Get a temp file name, don't leave the file open,
        # but don't delete it either, just to reserve the name.
        named_tempfile = tempfile.NamedTemporaryFile('wb', delete=False)    # keep after closing
        tempfilename = named_tempfile.name
        named_tempfile.close()

        # Write midifile to temp file (name)
        midifile.save(tempfilename)             # closes named_tempfile
        self.assertTrue(named_tempfile.file.closed)

        # read midifile back in to another BytesIO
        bio2 = io.BytesIO()
        with MidiFile(tempfilename) as midi2:   # closes it again
            midi2.save(file=bio2)
        self.assertFalse(bio2.closed)
        self.assertTrue(named_tempfile.file.closed)

        os.remove(named_tempfile.name)          # cleanup temp file

        # compare midifile(s)
        self.assertEqual(self.bio.getvalue(), bio2.getvalue())
示例#2
0
    def test_midifile_from_bytesIO(self):
        """Create MidiFile from `self.bio`; temporarily trap stdout and call `print_tracks()`;
        compare what was printed to expected value.
        """
        midifile = MidiFile(file=self.bio)

        _stdout = sys.stdout
        sio= io.StringIO()
        sys.stdout = sio
        midifile.print_tracks()
        sys.stdout = _stdout

        self.assertEqual(sio.getvalue(), self.expected_sio)
示例#3
0
    def __init__(self, midi_path, n_track=-1):

        self.midi_path = midi_path
        self.mid = MidiFile(midi_path)

        self.tempo = 0
        self.n_frames_per_tick = 0

        self.tick_per_beat = self.mid.ticks_per_beat
        self.n_frames_per_second = 250

        self.n_track = n_track
        if self.n_track >= len(self.mid.tracks):
            print(
                f"WARNING n_track = {self.n_track} larger than the amount of available tracks.\nLongest track used "
                f"instead.\n")
            self.n_track = -1
        if self.n_track == -1:
            max_len = -1
            for track in self.mid.tracks:
                if len(track) > max_len:
                    self.track = track
                    max_len = len(track)
        else:
            self.track = self.mid.tracks[self.n_track]
示例#4
0
    def __init__(self, midi_filename, arduino, floppy_array):
        """
        Creates and initializes the object

        """
        self.arduino = arduino
        self.midi_file = MidiFile(midi_filename)
        self.floppy_array = floppy_array
示例#5
0
    def load_file(self, filename):
        global PARSER
        PARSER = MidiFile(filename)

        with open(filename, 'rb') as f:
            # read in the binary file as a byte array
            ba = bytearray(f.read())

            # feed that into mido's parser
            p = mido.Parser()
            p.feed(ba)
            self.messages = []
            while p.pending():
                self.messages.append(p.get_message())
示例#6
0
class MidiPlayer(object):

    """
    This is the object that will send MIDI files to the floppy array for playback

    """

    def __init__(self, midi_filename, arduino, floppy_array):
        """
        Creates and initializes the object

        """
        self.arduino = arduino
        self.midi_file = MidiFile(midi_filename)
        self.floppy_array = floppy_array

    def play(self):
        """
        Plays the midi file on the floppy array. Currently this is just a blocking call.

        """
        channel_map = {}
        mapped_drives = 0
        floppies_per_track = max(len(self.floppy_array) / len([t for t in self.midi_file.tracks if len(t) > 20]), 1)
        for message in self.midi_file.play():
            try:
                print message

                if message.channel in channel_map:
                    drives = channel_map[message.channel]
                else:
                    drives = []
                    for x in xrange(floppies_per_track):
                        drives.append(self.floppy_array[mapped_drives])
                        mapped_drives += 1

                    channel_map[message.channel] = drives

                if message.type == 'note_on':
                    note = max(0, message.note)
                    for drive in drives:
                        drive.play_note(note, is_midi=True)
                elif message.type == 'note_off':
                    for drive in drives:
                        drive.play_note(0)
            except IndexError:
                pass  # sorry brah. MIDI file has more channels than you can handle
            except AttributeError:
                pass  # whateverz
        utils.reset(self.arduino)
示例#7
0
def mplay():
        global PLAYER
        pygame.midi.init()
        PLAYER = pygame.midi.Output(0)
        PLAYER.set_instrument(0, 1)
        
        # Store notes currently being played, so we know what they were when we turn them off
        notes_in_progress = {}  
        mid = MidiFile(FILE)
        for message in mid.play():
                if message.type == "note_on":
                        '''
                        notes_in_progress[message.note] = (message.note+PITCH_OFFSET, message.velocity+VOLUME_OFFSET) 
                        PLAYER.note_on(notes_in_progress[message.note][0], notes_in_progress[message.note][1], 1)
                        '''
                        if message.channel == 0:
                                PLAYER.note_on(message.note, message.velocity, 1)
                elif message.type == "note_off":
                        '''
                        PLAYER.note_off(notes_in_progress[message.note][0], notes_in_progress[message.note][1], 1)
                        del notes_in_progress[message.note]
                        '''
                        if message.channel == 0:
                                PLAYER.note_off(message.note, channel=1)
示例#8
0
from mido.midifiles import MidiFile, MidiTrack, MetaMessage
from mido.messages import Message
"""
    track.append(Message('note_on', note=value_code, velocity=80, time=32))
    track.append(Message('note_on', note=value_code, velocity=0, time=32))
"""

if __name__ == '__main__':
    out_path = "midi_files/Test1.mid"

    mid = MidiFile()
    track = MidiTrack()
    mid.tracks.append(track)

    # Tempo
    track.append(MetaMessage('set_tempo', tempo=800000, time=0))

    # Start A
    track.append(Message('note_on', note=23, velocity=80, time=0))
    # End A
    track.append(Message('note_on', note=23, velocity=0, time=560))

    # Start B
    track.append(Message('note_on', note=56, velocity=80, time=40))
    # End B
    track.append(Message('note_on', note=56, velocity=0, time=100))

    # Tempo
    track.append(MetaMessage('set_tempo', tempo=500000, time=0))

    # Start C
samplerate = s.samplerate

tolerance = 0.8

pitch_o = pitch("yin", win_s, hop_s, samplerate)
pitch_o.set_unit("midi")
pitch_o.set_tolerance(tolerance)

pitches = []
confidences = []

# Open file
output_file_name = "./data/pitches.txt"
output_file = open(output_file_name, "w")

with MidiFile() as mid:
    track = MidiTrack()
    mid.tracks.append(track)

    track.append(mido.Message('program_change', program=12, time=0))

    # total number of frames read
    total_frames = 0
    time = -1
    while True:
        samples, read = s()
        pitch = pitch_o(samples)[0]
        #pitch = int(round(pitch))
        confidence = pitch_o.get_confidence()
        #if confidence < 0.8: pitch = 0.
        print("%f %f %f" % (total_frames / float(samplerate), pitch, confidence))
示例#10
0
def load_file(filename):
    global PARSER
    PARSER = MidiFile(filename)
示例#11
0
"""
Open a MIDI file and print every message in every track.

Support for MIDI files is still experimental.
"""
import sys
from mido.midifiles import MidiFile

if __name__ == '__main__':
    filename = sys.argv[1]
    midi_file = MidiFile(filename)
    midi_file._print_tracks()