Exemple #1
0
def main():
    rootdir = './130000_Pop_Rock_Classical_Videogame_EDM_MIDI_Archive[6_19_15]/Metal_Rock_rock.freemidis.net_MIDIRip/midi/i/iron_maiden/'

    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            pattern = midi.read_midifile(rootdir + file)

            bass = midi.Pattern()

            drum = midi.Pattern()

            for track in pattern:
                for event in track:
                    if type(event) == midi.events.TrackNameEvent:
                        trackName = event.text.lower()

                        if trackName.find('bass') != -1:
                            bass.append(track)

                        if trackName.find('drum') != -1:
                            drum.append(track)

            midi.write_midifile('./bassMIDI/bass_' + file, bass)
            midi.write_midifile('./drumMIDI/drum_' + file, drum)

    return
Exemple #2
0
def test():
    """
    Make music!
    """
    initial = get_initial_state()
    node = get_successor_node(initial)
    for i in range(220):
        test_nodes = []
        for i in range(1000):
            test_nodes.append(get_successor_node(node))

        node = evaluate(node, test_nodes)

    pattern = midi.Pattern()
    pattern.make_ticks_abs()
    track = midi.Track()
    pattern.append(track)

    for note in node.action_path:
        on = midi.NoteOnEvent(tick=0, velocity=NOTE_VELOCITY, pitch=note)
        off = midi.NoteOffEvent(tick=NOTE_DURATION[get_rand_duration()],
                                pitch=note)
        track.append(on)
        track.append(off)

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    print(pattern)
    midi.write_midifile("example.mid", pattern)
    def get_pattern(self, time_scaling=Decimal(1.0), score_notes=True):
        events = []
        for note in self.score_notes if score_notes else self.played_notes:
            events.append(note.on_event)
            events.append(note.off_event)
        events = sorted(events)

        time_scalind = 10000
        current_time = None
        track = midi.Track()
        #track.append(midi.SetTempoEvent(tick=0, data=[7, 161, 32]))
        for time, is_off, note_number, vel in events:
            if current_time is None:
                current_time = time
            tick = int((time - current_time) * time_scaling)
            if is_off:
                track.append(
                    midi.NoteOffEvent(tick=tick,
                                      pitch=note_number,
                                      velocity=64))
            else:
                track.append(
                    midi.NoteOnEvent(tick=tick,
                                     pitch=note_number,
                                     velocity=vel))
            current_time = time

        track.append(midi.EndOfTrackEvent(tick=1))
        pattern = midi.Pattern()
        pattern.resolution = int(self.info['midiClockUnits'])
        pattern.append(track)
        return pattern
Exemple #4
0
    def data_to_song(self, song_name, song_data):
        """
        data_to_song takes a song in internal representation in the shape of
        [song_length, num_song_features] to a midi pattern
        all the features are retrieved to the settings in config 
        
        :param song_data: 
        :return: a midi pattern of song_data
        """

        midi_pattern = midi.Pattern([],
                                    resolution=int(
                                        self.output_ticks_per_quarter_note))
        cur_track = midi.Track([])
        cur_track.append(
            midi.events.SetTempoEvent(tick=0,
                                      bpm=self.config.melody_params.bpm))

        song_events_absolute_ticks = []
        abs_tick_note_beginning = 0
        for frame in song_data:
            ticks = int(round(frame[TICKS_FROM_PREV_START])
                        ) * 15 + self.config.melody_params.ticks_min
            if ticks > self.config.melody_params.ticks_max:
                ticks = self.config.melody_params.ticks_max
            abs_tick_note_beginning += ticks
            tick_len = int(round(
                frame[LENGTH])) * 15 + self.config.melody_params.length_min
            if tick_len > self.config.melody_params.length_max:
                tick_len = self.config.melody_params.length_max
            pitch = int(round(
                frame[FREQ])) + self.config.melody_params.pitch_min
            if pitch > self.config.melody_params.pitch_max:
                pitch = self.config.melody_params.pitch_max
            velocity = int(round(
                frame[VELOCITY])) + self.config.melody_params.velocity_min
            if velocity > self.config.melody_params.velocity_max:
                velocity = self.config.melody_params.velocity_max

            song_events_absolute_ticks.append(
                (abs_tick_note_beginning,
                 midi.events.NoteOnEvent(tick=0,
                                         velocity=velocity,
                                         pitch=pitch)))
            song_events_absolute_ticks.append(
                (abs_tick_note_beginning + tick_len,
                 midi.events.NoteOffEvent(tick=0, velocity=0, pitch=pitch)))

        song_events_absolute_ticks.sort(key=lambda e: e[0])
        abs_tick_note_beginning = 0
        for abs_tick, event in song_events_absolute_ticks:
            rel_tick = abs_tick - abs_tick_note_beginning
            event.tick = rel_tick
            cur_track.append(event)
            abs_tick_note_beginning = abs_tick

        cur_track.append(
            midi.EndOfTrackEvent(tick=int(self.output_ticks_per_quarter_note)))
        midi_pattern.append(cur_track)
        midi.write_midifile(song_name, midi_pattern)
Exemple #5
0
    def render(self):
        self.midi_data = midi.Pattern(resolution=self.song.ticks_per_beat *
                                      self.song.subticks_per_tick)

        for name, track in self.song.tracks.items():
            midi_track = self.add_midi_track(name, name, track)
            midi_track.render()
Exemple #6
0
    def to_pattern(self):
        track = midi.Track()
        pattern = midi.Pattern([track], resolution=config.resolution)

        time_signatures = time.signatures()

        rest_length = 0
        for i in range(config.song_length):
            if time_signatures.get(i, None) is not None:
                sig = time_signatures[i]
                track.append(midi.TimeSignatureEvent(data=[sig.numerator, sig.denominator, 36, 8]))

            if self._entities.get(i, None) is not None:
                entity = self._entities[i]
                if entity.is_note():
                    midi_val = entity.pitch().midi()
                    track.append(midi.NoteOnEvent(tick=rest_length, data=[midi_val, constants.DEFAULT_VELOCITY]))
                    track.append(midi.NoteOffEvent(tick=entity.length(), data=[midi_val, constants.DEFAULT_VELOCITY]))
                    rest_length = 0
                if entity.is_rest():
                    rest_length = entity.length()

        track.append(midi.EndOfTrackEvent(tick=0))

        return pattern
Exemple #7
0
def events_to_midi(events, resolution=None):
    """
    Given a set of MIDI event tuples, creates a MIDI pattern with the events in a single track.
    :param resolution: The resolution for the created MIDI pattern. If None, uses pyMIDI's default value.
    :param events: A series of NoteOn or NoteOff events
    :return: A MIDI pattern
    """
    if resolution is not None:
        pattern = midi.Pattern(resolution=resolution)
    else:
        pattern = midi.Pattern()
    track = midi.Track(events=[tuple_to_midi_event(e) for e in events])
    eot = midi.EndOfTrackEvent(tick=1)
    pattern.append(track)
    track.append(eot)
    return pattern
Exemple #8
0
def generate_random_midi():
    pattern = midi.Pattern(resolution=220)
    track = midi.Track()
    pattern.append(track)

    ticks = 0
    tick_buffer = 0
    pitches = [-1] * NEURAL_NET_DELAY  #use -1 to indicate a rest
    set_tempo = midi.SetTempoEvent()
    set_tempo.set_bpm(TEMPO)
    track.append(set_tempo)
    while ticks < NUM_TICKS:
        duration = random.randint(*DURATION_RANGE)
        volume = random.randint(*VOLUME_RANGE)
        pitch = random.randint(*PITCH_RANGE)
        if duration + ticks > NUM_TICKS:
            duration = NUM_TICKS - ticks

        ticks += duration
        tick_buffer += duration

        while tick_buffer > 0:
            tick_buffer -= TICKS_PER_WINDOW
            pitches.append(pitch - PITCH_RANGE[0])

        on = midi.NoteOnEvent(tick=0, velocity=volume, pitch=pitch)
        off = midi.NoteOffEvent(tick=duration, pitch=pitch)
        track.extend([on, off])

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    return (pattern, pitches)
def list_to_midi(chunk_str_list, generated_dir, filename):
    pattern = midi.Pattern(resolution=480)

    track = midi.Track()
    pattern.append(track)

    for chunk in chunk_str_list:
        chunk_info = chunk.split("_")
        event_type = chunk_info[1]

        if event_type == "no":
            tick = int(chunk_info[0])
            pitch = int(chunk_info[2])
            velocity = int(chunk_info[3])

            e = midi.NoteOnEvent(tick=tick, channel=0, velocity=velocity, pitch=pitch)
            track.append(e)

        elif event_type == "st":
            tick = int(chunk_info[0])
            bpm = int(chunk_info[2])
            mpqn = int(chunk_info[3])
            ev = midi.SetTempoEvent(tick=tick, bpm=bpm, mpqn=mpqn)
            track.append(ev)

        elif event_type == "cc":
            control = int(chunk_info[3])
            value = int(chunk_info[4])
            e = midi.ControlChangeEvent(channel=0, control=control, value=value)
            track.append(e)

    end_event = midi.EndOfTrackEvent(tick=1)
    track.append(end_event)

    midi.write_midifile(generated_dir + filename + '.mid', pattern)
Exemple #10
0
def noteStateMatrixToMidi(statematrix, name="example", span=span):
    statematrix = np.array(statematrix)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    span = upperBound - lowerBound
    tickscale = 55

    lastcmdtime = 0
    prevstate = [0 for x in range(span)]
    for time, state in enumerate(statematrix + [prevstate[:]]):
        offNotes = []
        onNotes = []
        for i in range(span):
            n = state[i]
            p = prevstate[i]
            if p == 1:
                if n == 0:
                    offNotes.append(i)
            elif n == 1:
                onNotes.append(i)
        for note in offNotes:
            track.append(midi.NoteOffEvent(tick=(time - lastcmdtime) * tickscale, pitch=note + lowerBound))
            lastcmdtime = time
        for note in onNotes:
            track.append(midi.NoteOnEvent(tick=(time - lastcmdtime) * tickscale, velocity=40, pitch=note + lowerBound))
            lastcmdtime = time

        prevstate = state

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    midi.write_midifile("{}.mid".format(name), pattern)
Exemple #11
0
def numpy2midi(numpy_path, filename, dur=100, velo=50, inst=1):
    """
    A numpy file that represents tones for a melody gets converted into a 
    midi file
    :param numpy_path: path of the numpy file
    :param filename: filename for midi output
    :param dur: duration of every tone (equidistant)
    :param velo: velocity of every tone
    :param inst: instrument (see:
    https://en.wikipedia.org/wiki/General_MIDI#Program_change_events)
    """

    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    data = np.loadtxt(numpy_path, dtype=np.int16)

    track.append(midi.ProgramChangeEvent(tick=0, channel=0, data=[inst]))

    # make equidistant tones with fixed velocity
    for d in data:
        track.append(midi.NoteOnEvent(tick=0, channel=0, data=[d, velo]))
        track.append(midi.NoteOffEvent(tick=dur, channel=0, data=[d, velo]))
    track.append(midi.EndOfTrackEvent(tick=1))

    midi.write_midifile(filename + ".mid", pattern)
def sample_midi(states, low=24, high=102, filename='new_music'):
    scale, last_update = 55, 0
    data = midi.Pattern()
    current = midi.Track()
    data.append(current)

    spectrum = high - low

    states = np.array(states)
    previous = [0 for i in range(spectrum)]
    for t, state in enumerate(states + [previous[:]]):
        off, on = [], []
        for i in range(spectrum):
            n = state[i]
            p = previous[i]
            if (p == 1):
                if (n == 0):
                    off.append(i)
            elif (n == 1):
                on.append(i)
        for note in off:
            current.append(
                midi.NoteOffEvent(tick=(t - last_update) * scale,
                                  pitch=note + low))
            last_update = t
        for note in on:
            current.append(
                midi.NoteOnEvent(tick=(t - last_update) * scale,
                                 velocity=40,
                                 pitch=note + low))

        previous = state
        end = midi.EndOfTrackEvent(tick=1)
        current.append(end)
        midi.write_midifile('{}.mid'.format(filename), data)
Exemple #13
0
def gen_multitracks(pattern):
    """
    将一个midi.Pattern类分成各个音轨
    """
    sub_patterns = []
    for track in pattern:
        _sub_pattern = midi.Pattern(format=pattern.format,
                                    resolution=pattern.resolution)
        _sub_pattern.append(pattern[0])  # basic info, usage not sure
        for idx, event in enumerate(track):
            #分离track
            if isinstance(event, midi.ProgramChangeEvent):
                try:
                    channel = event.channel
                    _sub_pattern.append(track)
                    #判断是旋律音色还是打击乐
                    program = event.data if channel != 9 else "Percusiion"
                    sub_pattern = {
                        'pattern': _sub_pattern,
                        'channel': channel,
                        'program': program
                    }
                    #分离track
                    sub_patterns.append(sub_pattern)
                    break
                except AttributeError:
                    pass
    return sub_patterns
Exemple #14
0
def demo():
    # 这个demo是把我们分出的单音色的Pattern标准化
    # 这样的Pattern有两个Track
    # Track0 仅有一些基本信息
    # Track1 包含了音乐本身
    midifile = "../track/Stan_1_Violin.mid"
    pattern = read_midifile(midifile)

    resolution = get_resolution(pattern)
    bpm = get_tempo(pattern)
    time_signature = get_time_signature(pattern)
    note = get_note(pattern[1])
    program = get_channel_program(pattern[1])  # [channel, program]

    # 输出Pattern的初始化
    pat = midi.Pattern(tracks=[[], []])

    pat = set_resolution(pat, resolution)
    pat = set_tempo(pat, bpm)
    pat = set_time_signature(pat, time_signature)
    pat[0].append(midi.EndOfTrackEvent(tick=0, data=[]))

    pat[1] = set_program(pat[1], channel=program[0], value=program[1])
    pat[1] = set_note(pat[1], note)

    # print(pattern[0])

    save_midfile(pat, "../test_std_Stan.mid")
def main():
  pattern = midi.Pattern()
  track = midi.Track()
  pattern.append(track)

  pitchs = [-4,1,3,5,8,6,5,3,3,5,6,5,1,1,5,8,13,15,12,10,8,8,3,5,1,5,8,13,15,12,10,8,8,10,13,13,13,13,8,5,5,5,6,8,3,5,3,5,6,8,3,5,3]
  pitchs = [p+60 for p in pitchs]
  tempos = [2,2,2,4,4,2,1,1,2,4,2,2,4,2,2,2,4,4,2,1,1,2,2,10,2,2,2,4,4,2,1,1,1,3,2,1,1,1,2,1,4,2,1,1,1,1,10,2,1,1,1,1,6]
  tempos = [2*x for x in tempos]
  print(len(pitchs))
  print(len(tempos))
  # repeats = [4, 3, 6, 3]
  print('resolution = ', pattern.resolution)
  idx = 0

  hmn = [0]
  pitchs = [tuple(p+i for i in hmn) for p in pitchs]
  print(pitchs)
  for _ in range(100):
    for ps, t in zip(pitchs, tempos):
      for p in ps:
        track_append(track, ON, 0, p)
      for idx, p in enumerate(ps):
        track_append(track, OFF, 55*t if idx==0 else 0, p)

  track_append(track, EOT, tick=1)
  midi.write_midifile("qingge.mid", pattern)
Exemple #16
0
 def matrixToMidi(self, matrix, name="example"):
     pattern = midi.Pattern()
     track = midi.Track()
     pattern.append(track)
     tickCounter = 0
     for i in range(len(matrix)):
         for j in range(len(matrix[i])):
             if (matrix[i][j] == 0).any():
                 if not (matrix[i][j] == 0).all():
                     #print("Couple found: ")
                     #print(matrix[i][j])
                     #print("Response: a zero")
                     event = midi.NoteOffEvent(tick=tickCounter,
                                               pitch=j + self._lowerBound)
                     track.append(event)
                     tickCounter = 0
                 #else:
                 #print("Couple found: ")
                 #print(matrix[i][j])
                 #print("Response: [0, 0]")
             else:
                 #print("Couple found: ")
                 #print(matrix[i][j])
                 #print("Response: [1, 1]")
                 velocity = int(matrix[i][j][1])
                 event = midi.NoteOnEvent(tick=tickCounter,
                                          velocity=velocity,
                                          pitch=j + self._lowerBound)
                 track.append(event)
                 tickCounter = 0
         tickCounter = tickCounter + 1
     endOfTrack = midi.EndOfTrackEvent(tick=1)
     track.append(endOfTrack)
     #print(pattern)
     midi.write_midifile("generated/abc{}.mid".format(name), pattern)
Exemple #17
0
def filter_ptrn_of_percussion(x,
                              typs=(midi.NoteOnEvent, midi.NoteOffEvent),
                              channel=9,
                              res=480):
    """
    Filter out note events that use channel 9 which corresponds to percussion
    """
    if isinstance(x, utils.MidiObj):
        x = x.ptrn
    x.make_ticks_abs()
    if isinstance(x, midi.Pattern):
        new_ptrn = copy_ptrn(x)
    else:
        new_ptrn = midi.Pattern(tick_relative=False, resolution=res)

    for old_trck in x:
        new_trck = midi.Track(tick_relative=False)
        new_ptrn.append(new_trck)
        for old_evnt in old_trck:
            keep = True
            if isinstance(old_evnt, typs) and old_evnt.channel == channel:
                keep = False
            if keep:
                new_evnt = copy.deepcopy(old_evnt)
                new_trck.append(new_evnt)
    x.make_ticks_rel()
    new_ptrn.make_ticks_rel()
    return new_ptrn
Exemple #18
0
def test_1():

    print("[%s:%d] test_1()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    file = "test.mid"

    pattern = midi.Pattern(resolution=960)  #このパターンがmidiファイルに対応しています。

    track = midi.Track()  #トラックを作ります
    pattern.append(track)  #パターンに作ったトラックを追加します。

    ev = midi.SetTempoEvent(tick=0, bpm=120)  #テンポを設定するイベントを作ります
    track.append(ev)  #イベントをトラックに追加します。

    e = midi.NoteOnEvent(tick=0, velocity=100,
                         pitch=midi.G_4)  #ソの音を鳴らし始めるイベントを作ります。
    track.append(e)

    e = midi.NoteOffEvent(tick=960, velocity=100,
                          pitch=midi.G_4)  #ソの音を鳴らし終えるイベントを作ります。
    track.append(e)

    eot = midi.EndOfTrackEvent(tick=1)  #トラックを終えるイベントを作ります
    track.append(eot)

    midi.write_midifile(file, pattern)  #パターンをファイルに書き込みます。
Exemple #19
0
    def store_track_as_file(self, base_path: str):

        pattern = midi.Pattern()

        pattern.resolution = self.resolutuion
        # ticks need to be relative for export
        self.track.make_ticks_rel()
        pattern.append(self.track)

        # create folder if it does not exist
        folder_path = base_path + self.relative_file_path
        if not path.exists(folder_path):
            os.makedirs(folder_path)

        # build filename
        if self.is_drum:
            export_filename = self.file_name[:-4] + "-" + str(
                self.file_id) + "-drum.mid"
        else:
            export_filename = self.file_name[:-4] + "-" + str(
                self.file_id
            ) + "-" + self.category.name + "-" + self.instrument.name + ".mid"

        midi.write_midifile(midifile=folder_path + export_filename,
                            pattern=pattern)
def generate_random_melody(end_tick, max_notes, min_init_pitch, max_init_pitch,
                           pitch_range, force_stop):
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    curr_tick = 0
    curr_note = 0
    curr_pitch = 0
    last_pitch = -1
    while curr_tick < end_tick and curr_note < max_notes:
        if last_pitch < 0:
            curr_pitch = random.randint(min_init_pitch, max_init_pitch)
        else:
            curr_pitch = last_pitch + random.randint(
                (pitch_range / 2) * -1, pitch_range / 2)
        on = midi.NoteOnEvent(tick=curr_tick, velocity=100, pitch=curr_pitch)
        track.append(on)
        last_for = end_tick / max_notes + random.randint(
            max_notes * -1, max_notes)
        curr_tick += last_for
        if curr_tick > end_tick and force_stop:
            curr_tick = end_tick
        off = midi.NoteOffEvent(tick=curr_tick, pitch=curr_pitch)
        track.append(off)
        last_pitch = curr_pitch
        curr_note += 1
    eot = midi.EndOfTrackEvent(tick=curr_tick)
    track.append(eot)
    return pattern
Exemple #21
0
def record(filename):
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    port = get_port()
    try:
        while True:
            event = read_event()
            if event:
                evtyp = event.name
                tick = event.tick
                velocity = event.velocity
                pitch = event.pitch
                track.append(event)
                if port and port.isOpen():
                    port.write(event)
                print(evtyp, 'tick:%s' % tick, 'velocity: %s' % velocity,
                      'pitch: %s' % pitch)
    finally:
        eot = midi.EndOfTrackEvent(tick=1)
        if pattern and track:
            track.append(eot)
            if port and port.isOpen():
                port.write(eot)
                port.close()
            midi.write_midifile(filename, pattern)
        else:
            print "S:omething's All F****d Up."
Exemple #22
0
def main():
    pattern = midi.read_midifile("1.mid")

    output = midi.Pattern(resolution=480)
    output.append(pattern[4])
    midi.write_midifile('temp.mid', output)
    print(output)
    return
    preprocessed = midi.Pattern(resolution=pattern.resolution)

    for idx, it in enumerate(pattern):
        if idx == 0:
            preprocessed.append(it)

    print(preprocessed)
    midi.write_midifile('ebubu.mid', preprocessed)
def notes_to_midi(midi_vals, fn):
    # Instantiate a MIDI Pattern (contains a list of tracks)
    pattern = midi.Pattern()
    pattern.resolution = 480
    # Instantiate a MIDI Track (contains a list of MIDI events)
    track = midi.Track()
    # Append the track to the pattern
    pattern.append(track)
    
    for val in midi_vals:
        vel = 0 if val == 0 else 100
        # Instantiate a MIDI note on event, append it to the track
        on = midi.NoteOnEvent(tick=0, velocity=vel, pitch=val)
        track.append(on)
            
        # Instantiate a MIDI note off event, append it to the track (1/16th note = 480/16 = 30 ticks)
        off = midi.NoteOffEvent(tick=120, pitch=val)
        track.append(off)

    # Add the end of track event, append it to the track
    eot = midi.EndOfTrackEvent(tick=0)
    track.append(eot)
    # Print out the pattern
    print pattern
    # Save the pattern to disk
    midi.write_midifile(fn, pattern)
Exemple #24
0
 def __init__(self, interval=120, velocity=100):
     self.interval = interval
     self.velocity = velocity
     self.chapterlength = 16
     self.pattern = midi.Pattern()
     self.track = midi.Track()
     self.pattern.append(self.track)
def mEventsToPattern(mevs):
    """
    Converting MEvents to a MIDI file. The following function takes a music structure
    (Music, Seq, Par, etc.) and converts it to a pythonmidi Pattern. File-writing is
    not performed at this step.
    :param mevs:
    :return:
    """
    pattern = midi.Pattern() # Instantiate a MIDI Pattern (contains a list of tracks)
    pattern.resolution = RESOLUTION # Set the tick per beat resolution
    pList = eventPatchList(mevs) # get list of active patches
    pmap = linearPatchMap(pList) # linear patch/channel assignment
    usedChannels = map(lambda p: p[1], pmap) # which channels are we using? (Important for drum track)
    mevsByPatch = splitByPatch(mevs, pList) # split event list by patch
    currChan = 0; # channel counter
    for i in range(0, len(pmap)):
        track = midi.Track()
        if currChan in usedChannels: # are we using this channel?
            # if yes, then we add events to it
            mevsP = mevsByPatch[i] # get the relevant collection of events
            if pmap[i][0][0] >= 0: # are we assigning an instrument?
                track.append(midi.ProgramChangeEvent(value=pmap[i][0][0])) # set the instrument
            mevsOnOff = mEventsToOnOff(mevsP) # convert to on/off messages
            onOffToRelDur(mevsOnOff) # convert to relative timestamps
            for e in mevsOnOff: # for each on/off event...
                m = toMidiEvent(e) # turn it into a pythonmidi event
                track.append(m) # add that event to the track
        currChan += 1 # increment channel counter
        track.append(midi.EndOfTrackEvent(tick=1)) # close the track (not optional!)
        pattern.append(track) # add the track to the pattern
    return pattern
def write_midi_from_log(input_filename, output_filename):
	pattern = midi.Pattern()
	started = False
	for (tick, velocity, pitch) in MidiEventParser(input_filename):
		if not started:
			started = True
			first = tick
		new_tick = tick-first
		if not velocity:
			event = midi.NoteOffEvent(tick=new_tick, pitch=eval('midi.{}'.format(pitch)))
		else:
			pattern = midi.Pattern()
			event = midi.NoteOnEvent(tick=new_tick, velocity=velocity, pitch=eval('midi.{}'.format(pitch)))
		track.append(event)
		pattern.append(track)
	midi.write_midifile(output_filename, pattern)
Exemple #27
0
    def piano_roll_to_midi(piano_roll, filename):
        """
        Saves a midi file from a piano_roll object

        :param piano_roll: A list of lists, where each sublist represents a time step and contains
            the midi numbers
        :param filename: The file name of the output file
        :return: The midi track that was created
        """
        pattern = midi.Pattern()
        track = midi.Track()
        pattern.append(track)
        offset = 0

        for time_step, notes in enumerate(piano_roll):
            for note in notes:
                previous_notes = piano_roll[time_step -
                                            1] if time_step > 0 else []
                if note not in previous_notes:
                    track.append(
                        midi.NoteOnEvent(tick=offset, velocity=100,
                                         pitch=note))
                    offset = 0
            offset += 130
            for note in notes:
                next_notes = piano_roll[
                    time_step + 1] if time_step < len(piano_roll) - 1 else []
                if note not in next_notes:
                    track.append(midi.NoteOffEvent(tick=offset, pitch=note))
                    offset = 0

        eot = midi.EndOfTrackEvent(tick=1)
        track.append(eot)
        midi.write_midifile(filename + '.mid', pattern)
        return track
Exemple #28
0
def midi_decode(grid):
    pattern = midi.Pattern()
    track = midi.Track()
    tempoEvent = midi.SetTempoEvent()
    tempoEvent.set_bpm(30)
    track.append(tempoEvent)
    pattern.append(track)

    previous_vector = grid[0] # first vector
    for note_index in range(len(previous_vector)):
        if previous_vector[note_index] != 0: #velocity is not 0
            track.append(midi.NoteOnEvent(tick=0, velocity=previous_vector[note_index], pitch=note_index))

    tickoffset = 0
    for vector in grid:
        if previous_vector == vector: #if vectors are same, no new events
            tickoffset += 1
        else:
            for note_index in range(len(previous_vector)):
                if previous_vector[note_index] == vector[note_index]: #if same velocity, hold the note rather than rearticulate (no new event)
                    continue
                if previous_vector[note_index] != 0 and vector[note_index] == 0:
                    if note_index > 127:
                        print "BROKEN ASSUMPTION"
                    track.append(midi.NoteOffEvent(tick=tickoffset, pitch=note_index))
                else:
                    track.append(midi.NoteOnEvent(tick=0, velocity=vector[note_index], pitch=note_index))
                tickoffset = 0
            tickoffset += 1
        previous_vector = vector
    track.append(midi.EndOfTrackEvent(tick=1))
    return pattern
Exemple #29
0
def main():
  pattern = midi.Pattern()
  track = midi.Track()
  pattern.append(track)

  pitchs = [-5,-5,-6,1,2,3,6,5,3,2,1,1,1,2,1,-7,1,4,-6,1,3,3,2,2,2,3,2,0,2,5,-7,2,3,2,1,1,1,2,1,-7,1,4,-6,1,-6,-6,-5,-5,-5,-5,-6,1,2,3,6,5,3,2,1,1,1,2,1,-7,1,4,-6,1,3,3,2,2,2,3,2,0,2,5,-7,2,3,2,1,1,1,2,1,-7,1,4,-6,1,2,2,1]
  convert = {0:2, 1:1, 2:3, 3:5, 4:6, 5:8, 6:10, -5:-4, -6:-2, -7:0}
  pitchs = [convert[x] for x in pitchs]
  pitchs = [p+60 for p in pitchs]
  tempos = [2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2]
  # tempos = [2*x for x in tempos]
  print(len(pitchs))
  print(len(tempos))
  # repeats = [4, 3, 6, 3]
  print('resolution = ', pattern.resolution)
  idx = 0

  hmn = [0]
  pitchs = [tuple(p+i for i in hmn) for p in pitchs]
  print(pitchs)
  for _ in range(100):
    for ps, t in zip(pitchs, tempos):
      for p in ps:
        track_append(track, ON, 0, p)
      for idx, p in enumerate(ps):
        track_append(track, OFF, 55*t if idx==0 else 0, p)

  track_append(track, EOT, tick=1)
  midi.write_midifile("shoushou.mid", pattern)
def main():

    composerName = "mozart"
    createNewTransition = False

    inputFiles = glob.glob('midis/midiworld/classic/' + composerName + '*.mid')
    if createNewTransition:
        getTransitionMatrix(inputFiles, composerName)

    lengthM = loadMatrixFromFile("matrices/" + composerName + "LengthM.dat")
    pitchM = loadMatrixFromFile("matrices/" + composerName + "PitchM.dat")
    velocityM = loadMatrixFromFile("matrices/" + composerName +
                                   "VelocityM.dat")

    notesList = highestPlausibility(lengthM, pitchM, velocityM)
    outFileName = "midis/" + composerName + "New.mid"

    # Instantiate a MIDI Pattern (contains a list of tracks)
    resolution = 384
    pattern = midi.Pattern(resolution=resolution)

    # Instantiate a MIDI Track (contains a list of MIDI events)
    track = midi.Track()

    # Append the track to the pattern
    pattern.append(track)

    # Set Instrument to piano
    pEvent = midi.ProgramChangeEvent(tick=0, channel=0)
    pEvent.set_value(1)
    track.append(pEvent)

    # Set tempo to 150 bpm
    tEvent = midi.SetTempoEvent(tick=0)
    tEvent.set_bpm(150)
    track.append(tEvent)

    for note in notesList:
        tick = Note.lengthToTick(note.length, resolution)
        pitch = note.pitch
        velocity = note.volume

        # Append the new note
        track.append(
            midi.NoteOnEvent(channel=0, tick=0, pitch=pitch,
                             velocity=velocity))
        # Stop the previous note to avoid unpleasant mixing
        track.append(
            midi.NoteOnEvent(channel=0, tick=tick, pitch=pitch, velocity=0))

    # Add the end of track event, append it to the track
    eot = midi.EndOfTrackEvent(tick=0)
    track.append(eot)

    print pattern
    # Save the pattern to disk
    midi.write_midifile(outFileName, pattern)

    print "\nMusic written to " + outFileName + "\n"