Ejemplo n.º 1
0
def vector_to_midi(vector):
    '''Given a np array (vector.data), returns a python midi pattern'''
    pattern = midi.Pattern(resolution=960)
    #first, separate tracks
    tracklist = {}
    for i in range(2, vector.shape[0], 4):
        for j in range(0, vector.shape[1]):
            track = vector[i:i + 4, j]
            if np.sum(track) > 0:
                instrument = int(track[0])
                print(instrument)
                if instrument not in tracklist:
                    tracklist[instrument] = np.vstack(
                        (vector[0:2, j].reshape(-1, 1), track.reshape(-1, 1)))
                    print('pop')
                else:
                    tracklist[instrument] = np.hstack(
                        (tracklist[instrument],
                         np.vstack((vector[0:2, j].reshape(-1, 1),
                                    track.reshape(-1, 1)))))

    for k, track in tracklist.items():
        miditrack = midi.Track()
        pattern.append(miditrack)
        bpm = track[1, 0]
        tempoevent = midi.SetTempoEvent(tick=0, bpm=bpm)
        miditrack.append(tempoevent)
        instrument = int(track[2, 0])
        fontevent = midi.ProgramChangeEvent(tick=0, value=instrument)
        miditrack.append(fontevent)
        if not np.array_equal(bpm * np.ones(track.shape[1]), track[1, :]):
            print('Tempo changes. Code assumes it doesn\'t. Contact Jingyi.')

        event_tick = 0
        track_duration = np.max(track[0, :] + track[-1, :])
        active_notes = {}
        start_times = track[0, :]
        for t in range(0, int(track_duration) + 1):
            for pitch in active_notes:
                active_notes[pitch] -= 1

            negs = [k for k, v in active_notes.items() if v < 0]
            for n in negs:
                active_notes.pop(n)

            while 0 in active_notes.values():
                pitches = [k for k, v in active_notes.items() if v == 0]
                for pitch in pitches:
                    off = midi.NoteOffEvent(tick=t - event_tick, pitch=pitch)
                    miditrack.append(off)
                    active_notes.pop(pitch)
                    event_tick = t

            #run through track to add on/off events
            if t in start_times:
                ni = np.where(t == start_times)
                for n in ni[0]:
                    note = track[:, n]
                    start_time = int(note[0])
                    pitch = int(note[2])
                    velocity = int(note[1])
                    duration = int(note[3])
                    active_notes[pitch] = duration
                    on = midi.NoteOnEvent(tick=t - event_tick,
                                          velocity=velocity,
                                          pitch=pitch)
                    miditrack.append(on)
                    event_tick = start_time

        miditrack.append(midi.EndOfTrackEvent(tick=0))
    return pattern
Ejemplo n.º 2
0
   midi.NoteOnEvent(tick=20, channel=0, data=[69, 0]),
   midi.NoteOnEvent(tick=100, channel=0, data=[66, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[74, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[68, 31]),
   midi.NoteOnEvent(tick=0, channel=0, data=[71, 37]),
   midi.NoteOnEvent(tick=240, channel=0, data=[71, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[68, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[69, 29]),
   midi.NoteOnEvent(tick=0, channel=0, data=[73, 33]),
   midi.NoteOnEvent(tick=120, channel=0, data=[64, 27]),
   midi.NoteOnEvent(tick=360, channel=0, data=[79, 33]),
   midi.NoteOnEvent(tick=480, channel=0, data=[79, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[69, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[73, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[64, 0]),
   midi.EndOfTrackEvent(tick=0, data=[])]),
  midi.Track(\
[    midi.NoteOnEvent(tick=1, channel=0, data=[57, 46]),
   midi.NoteOnEvent(tick=234, channel=0, data=[71, 36]),
   midi.NoteOnEvent(tick=1, channel=0, data=[57, 0]),
   midi.NoteOnEvent(tick=119, channel=0, data=[71, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[67, 36]),
   midi.NoteOnEvent(tick=120, channel=0, data=[67, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[61, 46]),
   midi.NoteOnEvent(tick=166, channel=0, data=[61, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[69, 34]),
   midi.NoteOnEvent(tick=120, channel=0, data=[69, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[67, 34]),
   midi.NoteOnEvent(tick=120, channel=0, data=[67, 0]),
   midi.NoteOnEvent(tick=0, channel=0, data=[62, 44]),
   midi.NoteOnEvent(tick=194, channel=0, data=[62, 0]),
Ejemplo n.º 3
0
                    ),
                    midi.NoteOffEvent(tick=50, channel=9, pitch=inum - 128),
                    midi.NoteOnEvent(
                        tick=0, channel=9, velocity=92, pitch=inum - 128
                    ),
                    midi.NoteOffEvent(tick=50, channel=9, pitch=inum - 128),
                ]
            )

        empty = False
        time = 100

    if not empty:
        time = 500

# Four drumbeats indicate the end of the track and that the music is
# going to loop.
for i in range(4):
    track.extend(
        [
            midi.NoteOnEvent(tick=20, channel=9, velocity=92, pitch=35),
            midi.NoteOffEvent(tick=20, channel=9, pitch=35),
        ]
    )

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

# Save the pattern to disk
midi.write_midifile("comparison.mid", pattern)
Ejemplo n.º 4
0
	def end_current_track(self):
		if self.current_track != "":
			eot = midi.EndOfTrackEvent(tick=1)
			self.current_track.append(eot)
Ejemplo n.º 5
0
   midi.NoteOnEvent(tick=102, channel=0, data=[75,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[75,27]),
   midi.NoteOnEvent(tick=105, channel=0, data=[75,28]),
   midi.NoteOnEvent(tick=92, channel=0, data=[75,28]),
   midi.NoteOnEvent(tick=104, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=118, channel=0, data=[76,29]),
   midi.NoteOnEvent(tick=97, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=83, channel=0, data=[76,27]),
   midi.NoteOnEvent(tick=87, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=89, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=89, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=89, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[76,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[77,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[77,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[77,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[77,28]),
   midi.NoteOnEvent(tick=90, channel=0, data=[77,28]),
   midi.NoteOnEvent(tick=91, channel=0, data=[77,28]),
   midi.EndOfTrackEvent(tick=0, channel=0, data=[0,0])])])

midi.write_midifile("newMusic.mid", pattern)
Ejemplo n.º 6
0
 def render(self):
     for item in self.track.items:
         item.visit_midi_track(self)
     self.midi_data_track.make_ticks_rel()
     self.midi_data_track.append(midi.EndOfTrackEvent(tick=1))
Ejemplo n.º 7
0
        if l in letters and first == 1:
            noteon = midi.NoteOnEvent(tick=0,channel=edoc[l],velocity=70,pitch=edop[l]+12)
            tra.append(noteon)
        elif l in letters and first != 1:
            noteon = midi.NoteOnEvent(tick=1,channel=edoc[l],velocity=70,pitch=edop[l]+12)
            tra.append(noteon)
        noteoff = midi.NoteOffEvent(tick=109,channel=edoc[l],pitch=edop[l]+12)
        tra.append(noteoff)
        first += 1
        
noteon = midi.NoteOnEvent(tick=1,channel=16,velocity=1,pitch=0)
tra.append(noteon)
noteoff = midi.NoteOffEvent(tick=880,channel=16,velocity=1,pitch=0)
tra.append(noteoff)
          
trackend = midi.EndOfTrackEvent(tick=1)
tra.append(trackend)
midi.write_midifile("melody-edo.mid", pat)

#chord1
pat = midi.Pattern()
tra = midi.Track()
pat.append(tra)

let1 = "evqfjpyrdlmg"

pitch = midi.PitchWheelEvent(tick=0,channel=edoc["e"],pitch=edos["e"])
tra.append(pitch)
pitch = midi.PitchWheelEvent(tick=0,channel=edoc["v"],pitch=edos["v"])
tra.append(pitch)
pitch = midi.PitchWheelEvent(tick=0,channel=edoc["q"],pitch=edos["q"])
Ejemplo n.º 8
0
   tempo, = unpack('>H', fin.read(2))
   print "Tempo", tempo
   if pattern is not None: track.append(midi.SetTempoEvent(bpm=tempo, tick=delay))
   delay = 0
 elif cmd == 0xFE:
   # PPQN (pulses per quarter note)
   # cmdTimeBase
   ppqn, = unpack('>H', fin.read(2))
   print "PPQN", ppqn
   if pattern is not None:
     pattern.resolution = ppqn
 elif cmd == 0xFF:
   # end track
   # cmdFinish
   print "End track"
   if pattern is not None: track.append(midi.EndOfTrackEvent(tick=delay))
   delay = 0
   break
 elif cmd < 0x90:
   # note
   if (cmd&0x88) == 0x88:
     # voice off
     voiceId = cmd & 0x07
     unk, = struct.unpack('>B', fin.read(1))
     #print "Voice off", voiceId, unk
     if pattern is not None:
       doNoteOff(voiceId, track, delay, voices)
     delay = 0
   elif (cmd&0x80) == 0x80:
     # voice off
     voiceId = cmd & 0x07
Ejemplo n.º 9
0
def toMidi(gspattern, midiMap=None, folderPath="output/", name=None):
    """ Function to write GSPattern instance to MIDI.

    Args:
        midiMap: mapping used to translate tags to MIDI pitch
        folderPath: folder where MIDI file is stored
        name: name of the file
    """

    import midi 
    # Instantiate a MIDI Pattern (contains a list of tracks)
    pattern = midi.Pattern(tick_relative=False,format=1)
    pattern.resolution=getattr(gspattern,'resolution' , 960)
    
    # Instantiate a MIDI Track (contains a list of MIDI events)
    track = midi.Track(tick_relative=False)
    
    
    track.append(midi.TimeSignatureEvent(numerator = gspattern.timeSignature[0],denominator=gspattern.timeSignature[1]))
    # obscure events
    # timeSignatureEvent.set_metronome(32)
    # timeSignatureEvent.set_thirtyseconds(4)
    
    track.append(midi.TrackNameEvent(text= gspattern.name))

    track.append(midi.SetTempoEvent(bpm=gspattern.bpm))

    # Append the track to the pattern
    pattern.append(track)
    beatToTick = pattern.resolution 
    for e in gspattern.events:

        startTick = int(beatToTick  * e.startTime)
        endTick   = int(beatToTick  * e.getEndTime()) 
        pitch = e.pitch
        channel=1
        if midiMap:
            pitch = midiMap[e.tag[0]]
        if midiMap is None:
            track.append(midi.NoteOnEvent(tick=startTick, velocity=e.velocity, pitch=pitch,channel=channel))
            track.append(midi.NoteOffEvent(tick=endTick, velocity=e.velocity, pitch=pitch,channel=channel))

    track.append(midi.EndOfTrackEvent(tick=int(gspattern.duration * beatToTick)))



    # make tick relatives
    track.sort(key=lambda e:e.tick)
    track.make_ticks_rel()

    # Save the pattern to disk

    if(not os.path.exists(folderPath)) : 
        os.makedirs(folderPath)
    name = name or gspattern.name
    name = name or "test"
    if not ".mid" in name:
        name+=".mid"
    exportedPath = os.path.join(folderPath,name)
    
    midi.write_midifile(exportedPath, pattern)
    return exportedPath
Ejemplo n.º 10
0
def process(input_path, output_path, resolution):
    output = midi.Pattern(resolution=resolution)
    print(resolution)

    melody_track = midi.Track()
    melody_track.append(midi.ProgramChangeEvent(tick=0, data=[53], channel=0))
    guitar_track = midi.Track()
    guitar_track.append(midi.ProgramChangeEvent(tick=0, data=[29], channel=1))
    piano_track = midi.Track()
    piano_track.append(midi.ProgramChangeEvent(tick=0, data=[0], channel=2))
    bass_track = midi.Track()
    bass_track.append(midi.ProgramChangeEvent(tick=0, data=[34], channel=3))
    drum_track = midi.Track()
    # drum_track.append(midi.TrackNameEvent(tick=0, text='tk10', data=[116, 107, 49, 48]))
    # drum_track.append(midi.PortEvent(tick=0, data=[0]))
    # drum_track.append(midi.ChannelPrefixEvent(tick=0, data=[9]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[0, 127]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[32, 0]))
    drum_track.append(midi.ProgramChangeEvent(tick=0, channel=9, data=[1]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[7, 110]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[11, 100]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[91, 34]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 29]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 28]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 47]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 121]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 24]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 47]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 60]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 24]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 45]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 64]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 24]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 43]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 63]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 28]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 40]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 53]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 28]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 57]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 84]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 24]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 42]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 60]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 24]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 46]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 59]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 24]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 49]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 59]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 28]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 49]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 19]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 28]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 51]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 95]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[99, 29]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[98, 55]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[6, 60]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[101, 127]))
    # drum_track.append(midi.ControlChangeEvent(tick=0, channel=9, data=[100, 127]))

    with open(input_path, 'r') as f:
        rdr = csv.reader(f)

        cur_tick = 0.0
        plus_tick_per_time_slice = 0.0205 * resolution
        print(plus_tick_per_time_slice)

        lines = 0
        for line in rdr:
            lines += 1
            ones = [i for i, x in enumerate(line) if x == '1']
            for i in ones:
                if 0 <= i < 128:
                    melody_track.append(
                        midi.NoteOnEvent(tick=0, data=[i, 70], channel=0))
                elif 128 <= i < 256:
                    melody_track.append(
                        midi.NoteOffEvent(tick=0, data=[i - 128, 0],
                                          channel=0))
                elif 0 <= i - 356 < 128:
                    guitar_track.append(
                        midi.NoteOnEvent(tick=0, data=[i - 356, 30],
                                         channel=1))
                elif 128 <= i - 356 < 256:
                    guitar_track.append(
                        midi.NoteOffEvent(tick=0,
                                          data=[i - 356 - 128, 0],
                                          channel=1))
                elif 0 <= i - 356 * 2 < 128:
                    piano_track.append(
                        midi.NoteOnEvent(tick=0,
                                         data=[i - 356 * 2, 30],
                                         channel=2))
                elif 128 <= i - 356 * 2 < 256:
                    piano_track.append(
                        midi.NoteOffEvent(tick=0,
                                          data=[i - 356 * 2 - 128, 0],
                                          channel=2))
                elif 0 <= i - 356 * 3 < 128:
                    bass_track.append(
                        midi.NoteOnEvent(tick=0,
                                         data=[i - 356 * 3, 30],
                                         channel=3))
                elif 128 <= i - 356 * 3 < 256:
                    bass_track.append(
                        midi.NoteOffEvent(tick=0,
                                          data=[i - 356 * 3 - 128, 0],
                                          channel=3))
                elif 0 <= i - 356 * 4 < 128:
                    drum_track.append(
                        midi.NoteOnEvent(tick=0,
                                         data=[i - 356 * 4, 30],
                                         channel=9))
                elif 128 <= i - 356 * 4 < 256:
                    drum_track.append(
                        midi.NoteOffEvent(tick=0,
                                          data=[i - 356 * 4 - 128, 0],
                                          channel=9))

            prev_tick = cur_tick
            cur_tick += plus_tick_per_time_slice
            plus_tick = int(cur_tick - prev_tick)

            melody_track[-1].tick += plus_tick
            guitar_track[-1].tick += plus_tick
            piano_track[-1].tick += plus_tick
            bass_track[-1].tick += plus_tick
            drum_track[-1].tick += plus_tick
        print(lines)
        print(cur_tick)

    melody_track.append(midi.EndOfTrackEvent(tick=0, channel=0))
    guitar_track.append(midi.EndOfTrackEvent(tick=0, channel=1))
    piano_track.append(midi.EndOfTrackEvent(tick=0, channel=2))
    bass_track.append(midi.EndOfTrackEvent(tick=0, channel=3))
    drum_track.append(midi.EndOfTrackEvent(tick=0, channel=9))

    output.append(melody_track)
    output.append(guitar_track)
    output.append(piano_track)
    output.append(bass_track)
    output.append(drum_track)

    midi.write_midifile(output_path, output)
Ejemplo n.º 11
0
def main(argv):
    import getopt
    from wavestream import WaveReader

    def usage():
        print(
            'usage: %s [-M|-F] [-n pitchmin] [-m pitchmax] [-t threshold] '
            '[-o out.mid] [-w wsize] [-p instru] wav ...' % argv[0])
        return 100

    try:
        (opts, args) = getopt.getopt(argv[1:], 'MFn:m:t:o:w:p:')
    except getopt.GetoptError:
        return usage()
    pitchmin = 70
    pitchmax = 400
    threshold = 0.95
    outpath = 'out.mid'
    wsize = 50
    instru = 0
    attack = 70
    release = 70
    for (k, v) in opts:
        if k == '-M': (pitchmin, pitchmax) = (75, 200)  # male voice
        elif k == '-F': (pitchmin, pitchmax) = (150, 300)  # female voice
        elif k == '-n': pitchmin = int(v)
        elif k == '-m': pitchmax = int(v)
        elif k == '-t': threshold = float(v)
        elif k == '-o': outpath = v
        elif k == '-w': wsize = int(v)
        elif k == '-p': instru = int(v)
    contour = None
    for path in args:
        src = WaveReader(path)
        if contour is None:
            contour = PitchContour(src.framerate,
                                   pitchmin=pitchmin,
                                   pitchmax=pitchmax,
                                   threshold=threshold)
        contour.load(src.readraw(), src.nframes)
        src.close()
    #
    events = [midi.ProgramChangeEvent(tick=0, channel=0, data=[instru])]
    window = []
    km0 = 0
    kt = 0
    kd = 0
    for p in contour.segments:
        if p == 0:
            k = 0
        else:
            i = getpt(FRANGES, p)
            (_, k) = FRANGES[i - 1]
        #print '%d/%d' % (p,k),
        window.append(k)
        if len(window) < wsize: continue
        window = window[1:]
        km1 = majority(window)
        if km0 == km1:
            kd += 1
        else:
            print km0, kd
            if km0 == 0:
                kt += kd
            else:
                events.append(
                    midi.NoteOnEvent(tick=kt, channel=0, data=[km0, attack]))
                events.append(
                    midi.NoteOffEvent(tick=kd, channel=0, data=[km0, release]))
                kt = 0
            kd = 0
            km0 = km1
    events.append(midi.EndOfTrackEvent(tick=0, data=[]))
    pat = midi.Pattern(tracks=[events])
    midi.write_midifile(outpath, pat)
    return
Ejemplo n.º 12
0
 def finish(self, filename):
     # "All Notes End" event
     self.track.append(midi.ControlChangeEvent(tick=0, control=123))
     self.track.append(midi.EndOfTrackEvent(tick=1))
     midi.write_midifile(filename, self.pattern)
Ejemplo n.º 13
0
def write_midifile(melody, chords, pattern, filename):
    beat = 4

    def get_chord_pitches(chord):
        base = chord_base[chord[0]]
        if 'm' in chord:
            return (base, base + 3, base + 7)
        else:
            return (base, base + 4, base + 7)

    pattern = copy.deepcopy(pattern)
    del pattern[1]
    track_melody = midi.Track()
    pattern.append(track_melody)

    track_melody.append(midi.ProgramChangeEvent(tick=0, value=0, channel=0))
    track_melody.append(
        midi.TrackNameEvent(tick=0,
                            text='Track 1#',
                            data=[84, 114, 97, 99, 107, 32, 49]))

    pre_note = None
    for note in melody:
        if pre_note != None:
            tick = int(
                (note.position - pre_note.position) * pattern.resolution)
            track_melody.append(
                midi.NoteOffEvent(tick=tick, pitch=pre_note.pitch, channel=0))
        track_melody.append(
            midi.NoteOnEvent(tick=0, velocity=100, pitch=note.pitch,
                             channel=0))
        pre_note = note
    track_melody.append(
        midi.NoteOffEvent(tick=pattern.resolution * 1,
                          pitch=pre_note.pitch,
                          channel=0))
    track_melody.append(midi.EndOfTrackEvent(tick=0, channel=0))

    track_chord = midi.Track()
    pattern.append(track_chord)
    track_chord.append(midi.ProgramChangeEvent(tick=0, value=0, channel=1))
    track_chord.append(
        midi.TrackNameEvent(tick=0,
                            text='Track 2#',
                            data=[84, 114, 97, 99, 107, 32, 49],
                            channel=1))
    pre_chord = None
    for chord in chords:
        if pre_chord != None:
            tick = int((chord[0] - pre_chord[0]) * pattern.resolution)
            track_chord.append(
                midi.NoteOnEvent(tick=tick, velocity=0, pitch=0, channel=1))

            for pitch in get_chord_pitches(pre_chord[1]):
                track_chord.append(
                    midi.NoteOnEvent(tick=0,
                                     velocity=0,
                                     pitch=pitch,
                                     channel=1))

        for pitch in get_chord_pitches(chord[1]):
            track_chord.append(
                midi.NoteOnEvent(tick=0, velocity=80, pitch=pitch, channel=1))
        pre_chord = chord
    for i, pitch in enumerate(get_chord_pitches(pre_chord[1])):
        track_chord.append(
            midi.NoteOnEvent(tick=pattern.resolution * beat if i == 0 else 0,
                             velocity=0,
                             pitch=pitch,
                             channel=1))
    track_chord.append(midi.EndOfTrackEvent(tick=0, channel=1))

    midi.write_midifile(filename, pattern)
Ejemplo n.º 14
0
def compose(pitchInputFileName, rhythmInputFileName, outputFileName,
            songLength):
    pitchTransitions = Markov(pitchInputFileName)
    pithOrder = pitchTransitions.order()
    rhythmTransitions = Markov(rhythmInputFileName)
    rhythmOrder = rhythmTransitions.order()

    print "Markovs loaded into memmory"

    # Build random beging of song
    chords = []
    for i in range(pithOrder):
        chords.append([random.randint(50, 60)])
    # Build list of chords
    while (len(chords) < songLength):
        newChord = pitchTransitions.get(chords[-pithOrder:])
        if newChord is not None:
            newChord = ast.literal_eval(newChord)
            chords.append(newChord)
        else:
            print "INFO: No possible pitch/chord found"
            del chords[-1]
            chords.append([random.randint(50, 60)])
    # prettier endings
    chords[-1] = chords[-2]

    # Create begining of rhythm track
    rhythms = []
    for i in range(rhythmOrder):
        rhythms.append(4)
    # Build list of note lengths
    while (len(rhythms) < songLength):
        newLength = rhythmTransitions.get(rhythms[-rhythmOrder:])
        if newLength is not None:
            newLength = int(newLength)
            rhythms.append(newLength)
        else:
            print "INFO: No possible rhythm found"
            del rhythms[-1]
    #SONG SHOULD END WITH HOLE NOTE
    rhythms[-1] = 16
    rhythms[-2] = 16

    print "Song Composed:"

    # Make patern into
    pattern = midi.Pattern()
    pattern.make_ticks_abs()
    track = midi.Track()
    pattern.append(track)

    for i in range(songLength):
        length = int((220 / 16) * rhythms[i])
        # for pitch in chords[i]:
        for pitch in chords[i]:
            on = midi.NoteOnEvent(tick=0, velocity=NOTE_VELOCITY, pitch=pitch)
            track.append(on)
        for pitch in chords[i]:
            off = midi.NoteOffEvent(tick=length, pitch=pitch)
            track.append(off)

    eot = midi.EndOfTrackEvent(tick=0)
    track.append(eot)
    midi.write_midifile(outputFileName, pattern)

    print "Song written to file: %s" % outputFileName
Ejemplo n.º 15
0
import midi

MARY_MIDI = midi.Pattern(
    tracks=[[
        midi.TimeSignatureEvent(tick=0, data=[4, 2, 24, 8]),
        midi.KeySignatureEvent(tick=0, data=[0, 0]),
        midi.EndOfTrackEvent(tick=1, data=[])
    ],
            [
                midi.ControlChangeEvent(tick=0, channel=0, data=[91, 58]),
                midi.ControlChangeEvent(tick=0, channel=0, data=[10, 69]),
                midi.ControlChangeEvent(tick=0, channel=0, data=[0, 0]),
                midi.ControlChangeEvent(tick=0, channel=0, data=[32, 0]),
                midi.ProgramChangeEvent(tick=0, channel=0, data=[24]),
                midi.NoteOnEvent(tick=0, channel=0, data=[64, 72]),
                midi.NoteOnEvent(tick=0, channel=0, data=[55, 70]),
                midi.NoteOnEvent(tick=231, channel=0, data=[64, 0]),
                midi.NoteOnEvent(tick=25, channel=0, data=[62, 72]),
                midi.NoteOnEvent(tick=231, channel=0, data=[62, 0]),
                midi.NoteOnEvent(tick=25, channel=0, data=[60, 71]),
                midi.NoteOnEvent(tick=231, channel=0, data=[60, 0]),
                midi.NoteOnEvent(tick=25, channel=0, data=[62, 79]),
                midi.NoteOnEvent(tick=206, channel=0, data=[55, 0]),
                midi.NoteOnEvent(tick=25, channel=0, data=[62, 0]),
                midi.NoteOnEvent(tick=25, channel=0, data=[64, 85]),
                midi.NoteOnEvent(tick=0, channel=0, data=[55, 79]),
                midi.NoteOnEvent(tick=231, channel=0, data=[64, 0]),
                midi.NoteOnEvent(tick=25, channel=0, data=[64, 78]),
                midi.NoteOnEvent(tick=231, channel=0, data=[64, 0]),
                midi.NoteOnEvent(tick=25, channel=0, data=[64, 74]),
                midi.NoteOnEvent(tick=462, channel=0, data=[55, 0]),
def main():
    line_re = r"(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{6}) IP (?P<src>\d+\.\d+\.\d+\.\d+)\.(?P<sport>\d+) > (?P<dst>\d+\.\d+\.\d+\.\d+)\.(?P<dport>\d+): (?:Flags \[(?P<flags>[SFPRUWE\.]+)\])?.+?length (?P<length>\d+)"

    arg_parser = argparse.ArgumentParser(description="MIDI from tcpdump")
    arg_parser.add_argument('-f',
                            help="Output file, omit or give - for stdout",
                            metavar='file',
                            default='-')
    args = arg_parser.parse_args()

    if args.f == '-':
        output_file = sys.stdout
    else:
        output_file = open(args.f, 'w')
# To add track you can copy the first track (track = midi.Track() pattern.append(track)) an change the number behind.
    pattern = midi.Pattern()
    ###########################
    track = midi.Track()
    pattern.append(track)
    ###########################
    track2 = midi.Track()
    pattern.append(track2)
    track3 = midi.Track()
    pattern.append(track3)
    track4 = midi.Track()
    pattern.append(track4)
    track5 = midi.Track()
    pattern.append(track5)
    track6 = midi.Track()
    pattern.append(track6)
    track7 = midi.Track()
    pattern.append(track7)
    """track8 = midi.Track()
    pattern.append(track8)
    track9 = midi.Track()
    pattern.append(track9)
    track10 = midi.Track()
    pattern.append(track10)
    track11 = midi.Track()
    pattern.append(track11)
    track12 = midi.Track()
    pattern.append(track12)
    track13 = midi.Track()
    pattern.append(track13)
    track14 = midi.Track()
    pattern.append(track14)
    track15 = midi.Track()
    pattern.append(track15)"""

    last_time = datetime.now()
    line = sys.stdin.readline()
    while line:
        match = re.match(line_re, line)
        if match:
            data = match.groupdict()

            # Get the difference between now and the last event
            now = datetime.strptime(data['timestamp'], '%H:%M:%S.%f')

            spacing = int((now - last_time).microseconds / 1000.0)
            last_time = now

            if spacing < MIN_SPACING:
                spacing = MIN_SPACING

            # Determine note length based on packet length
            pkt_length = int(data.get('length', 0))
            note_length = int(pow(pkt_length, 0.75))

            if note_length < MIN_LENGTH:
                note_length = MIN_LENGTH

            # determine the note to play based on TCP flags
            note = midi.E_3  # Modifire midi.C_3 to midi.E_3
            flags = data.get('flags', '')
            if flags:  # You can change the note D C G F how do you want.
                if 'S' in flags:
                    note = midi.D_5
                elif '.' in flags:
                    note = midi.C_5
                elif 'F' in flags:
                    note = midi.G_5
                elif 'R' in flags:
                    note = midi.F_5

            # Determine the octave based on the src and dst IPs
            octave = hash((data['src'], data['dst'])) % 6 + 2
            note = note + octave * 5

            if note > MAX_OCTAVE:
                note = MAX_OCTAVE

            # Finally, append the note to the track, Velocity is between 0 and 127 also just copy the first 3 lines to add an track don't forget to change the number behind track.
            track.append(midi.NoteOnEvent(tick=800, velocity=127, pitch=50))
            track.append(midi.NoteOffEvent(tick=800, pitch=50))
            track.append(midi.ProgramChangeEvent(data=[115]))

            track2.append(
                midi.NoteOnEvent(tick=200, velocity=127, pitch=midi.C_3))
            track2.append(midi.NoteOffEvent(tick=200, pitch=midi.C_3))
            track2.append(midi.ProgramChangeEvent(data=[120]))

            track3.append(midi.NoteOnEvent(tick=400, velocity=50, pitch=note))
            track3.append(midi.NoteOffEvent(tick=400, pitch=note))
            track3.append(midi.ProgramChangeEvent(data=[0]))

            track4.append(midi.NoteOnEvent(tick=200, velocity=50, pitch=note))
            track4.append(midi.NoteOffEvent(tick=400, pitch=note))
            track4.append(midi.ProgramChangeEvent(data=[27]))

            track5.append(midi.NoteOnEvent(tick=400, velocity=100, pitch=note))
            track5.append(midi.NoteOffEvent(tick=800, pitch=note))
            track5.append(midi.ProgramChangeEvent(data=[53]))

            track6.append(midi.NoteOnEvent(tick=200, velocity=50, pitch=note))
            track6.append(midi.NoteOffEvent(tick=400, pitch=note))
            track6.append(midi.ProgramChangeEvent(data=[32]))

            track7.append(midi.NoteOnEvent(tick=0, velocity=75, pitch=note))
            track7.append(midi.NoteOffEvent(tick=100, pitch=note))
            track7.append(midi.ProgramChangeEvent(data=[72]))

#track8.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track8.append(midi.NoteOffEvent(tick=500, pitch=note))
#track8.append(midi.ProgramChangeEvent(data=[52]))

#track9.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track9.append(midi.NoteOffEvent(tick=500, pitch=note))
#track9.append(midi.ProgramChangeEvent(data=[52]))

#track10.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track10.append(midi.NoteOffEvent(tick=500, pitch=note))
#track10.append(midi.ProgramChangeEvent(data=[52]))

#track11.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track11.append(midi.NoteOffEvent(tick=500, pitch=note))
#track11.append(midi.ProgramChangeEvent(data=[52]))

#track12.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track12.append(midi.NoteOffEvent(tick=500, pitch=note))
#track12.append(midi.ProgramChangeEvent(data=[52]))

#track13.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track13.append(midi.NoteOffEvent(tick=500, pitch=note))
#track13.append(midi.ProgramChangeEvent(data=[52]))

#track14.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track14.append(midi.NoteOffEvent(tick=500, pitch=note))
#track14.append(midi.ProgramChangeEvent(data=[52]))

#track15.append(midi.NoteOnEvent(tick=0, velocity=100, pitch=note))
#track15.append(midi.NoteOffEvent(tick=500, pitch=note))
#track15.append(midi.ProgramChangeEvent(data=[52]))

        line = sys.stdin.readline()

    # Dump MIDI track to stdout add the track.append(midi.EndOfTrackEvent(tick=1)) and change the number behind the track to add a track
    track.append(midi.EndOfTrackEvent(tick=1))
    track2.append(midi.EndOfTrackEvent(tick=1))
    track3.append(midi.EndOfTrackEvent(tick=1))
    track4.append(midi.EndOfTrackEvent(tick=1))
    track5.append(midi.EndOfTrackEvent(tick=1))
    track6.append(midi.EndOfTrackEvent(tick=1))
    track7.append(midi.EndOfTrackEvent(tick=1))
    # track8.append(midi.EndOfTrackEvent(tick=1))
    # track9.append(midi.EndOfTrackEvent(tick=1))
    # track10.append(midi.EndOfTrackEvent(tick=1))
    # track11.append(midi.EndOfTrackEvent(tick=1))
    # track12.append(midi.EndOfTrackEvent(tick=1))
    # track13.append(midi.EndOfTrackEvent(tick=1))
    # track14.append(midi.EndOfTrackEvent(tick=1))
    # track15.append(midi.EndOfTrackEvent(tick=1))
    midi.write_midifile(output_file, pattern)

    return 0
Ejemplo n.º 17
0
def main():
    line_re = r"(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{6}) IP (?P<src>\d+\.\d+\.\d+\.\d+)\.(?P<sport>\d+) > (?P<dst>\d+\.\d+\.\d+\.\d+)\.(?P<dport>\d+): (?:Flags \[(?P<flags>[SFPRUWE\.]+)\])?.+?length (?P<length>\d+)"

    arg_parser = argparse.ArgumentParser(description="MIDI from tcpdump")
    arg_parser.add_argument('-f',
                            help="Output file, omit or give - for stdout",
                            metavar='file',
                            default='-')
    args = arg_parser.parse_args()

    if args.f == '-':
        output_file = sys.stdout
    else:
        output_file = open(args.f, 'w')

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

    last_time = datetime.now()
    line = sys.stdin.readline()
    while line:
        match = re.match(line_re, line)
        if match:
            data = match.groupdict()

            # Get the difference between now and the last event
            now = datetime.strptime(data['timestamp'], '%H:%M:%S.%f')

            spacing = int((now - last_time).microseconds / 1000.0)
            last_time = now

            if spacing < MIN_SPACING:
                spacing = MIN_SPACING

            # Determine note length based on packet length
            pkt_length = int(data.get('length', 0))
            note_length = int(pow(pkt_length, 0.75))

            if note_length < MIN_LENGTH:
                note_length = MIN_LENGTH

            # determine the note to play based on TCP flags
            note = midi.C_3
            flags = data.get('flags', '')
            if flags:
                if 'S' in flags:
                    note = midi.D_3
                elif '.' in flags:
                    note = midi.C_3
                elif 'F' in flags:
                    note = midi.G_3
                elif 'R' in flags:
                    note = midi.F_3

            # Determine the octave based on the src and dst IPs
            octave = hash((data['src'], data['dst'])) % 6 + 2
            note = note + octave * 12

	    if note > MAX_OCTAVE:
		note  = MAX_OCTAVE

            # Finally, append the note to the track
            track.append(midi.NoteOnEvent(tick=0, velocity=70, pitch=note))
            track.append(midi.NoteOffEvent(tick=300, pitch=note))
	    track.append(midi.ProgramChangeEvent(data=[0]))

	    track2.append(midi.NoteOnEvent(tick=50, velocity=70, pitch=note))
            track2.append(midi.NoteOffEvent(tick=90, pitch=note))
	    track2.append(midi.ProgramChangeEvent(data=[19]))
	    


        line = sys.stdin.readline()

    # Dump MIDI track to stdout
    track.append(midi.EndOfTrackEvent(tick=1))
    track2.append(midi.EndOfTrackEvent(tick=1))
    midi.write_midifile(output_file, pattern)
    

    return 0
Ejemplo n.º 18
0
    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(file, pattern)
Ejemplo n.º 19
0
def end_midi():
    # Add the end of track event, append it to the track
    global track
    eot = midi.EndOfTrackEvent(tick=0)
    track.append(eot)
Ejemplo n.º 20
0
def roll_to_midi(rolls, tick_per_time_slice, resolution=120):
    # melody is index 0
    # guitar is index 1
    # piano is index 2
    # bass is index 3
    # drum is index 4

    result = midi.Pattern(resolution=resolution * 100)
    for i in range(5):
        if i >= len(rolls):
            continue

        roll = rolls[i]
        channel = i

        # for drum
        if channel == 4:
            channel = 9

        track = midi.Track()
        if i == 0:
            track.append(
                midi.ProgramChangeEvent(tick=0, data=[53], channel=channel))
        elif i == 1:
            track.append(
                midi.ProgramChangeEvent(tick=0, data=[29], channel=channel))
        elif i == 2:
            track.append(
                midi.ProgramChangeEvent(tick=0, data=[0], channel=channel))
        elif i == 3:
            track.append(
                midi.ProgramChangeEvent(tick=0, data=[34], channel=channel))
        else:
            track.append(
                midi.ProgramChangeEvent(tick=0, data=[1], channel=channel))

        current_tick = 0
        prev_intensity = [0 for _ in range(128)]
        prev_tick = 0

        for time_slice in range(roll.shape[1]):
            for pitch in range(roll.shape[0]):
                if roll[pitch][time_slice] != prev_intensity[pitch]:
                    diff_tick = current_tick - prev_tick
                    if roll[pitch][time_slice] == 0:
                        track.append(
                            midi.NoteOffEvent(
                                tick=diff_tick,
                                data=[pitch, prev_intensity[pitch]],
                                channel=channel))
                        prev_intensity[pitch] = 0
                        prev_tick = current_tick
                    else:
                        if prev_intensity[pitch] == 0:
                            track.append(
                                midi.NoteOnEvent(
                                    tick=diff_tick,
                                    data=[pitch, roll[pitch][time_slice]],
                                    channel=channel))
                            prev_intensity[pitch] = roll[pitch][time_slice]
                            prev_tick = current_tick
                        else:
                            track.append(
                                midi.NoteOffEvent(
                                    tick=diff_tick,
                                    data=[pitch, prev_intensity[pitch]],
                                    channel=channel))
                            track.append(
                                midi.NoteOnEvent(
                                    tick=diff_tick,
                                    data=[pitch, roll[pitch][time_slice]],
                                    channel=channel))
                            prev_intensity[pitch] = roll[pitch][time_slice]
                            prev_tick = current_tick
                current_tick += tick_per_time_slice

        track.append(midi.EndOfTrackEvent(tick=0, channel=channel))
        # if i == 1:
        result.append(track)
    return result
Ejemplo n.º 21
0
 def trackToMidi(track, name="sample"):
     pattern = midi.Pattern()
     pattern.append(track)
     track.append(midi.EndOfTrackEvent(tick=1))
     midi.write_midifile(name, pattern)
Ejemplo n.º 22
0
def conv_text_to_midi(filename):
	if os.path.exists(filename[:-4]+'.mid'):
		return
	f = open(filename, 'r')
	f.readline() # title
	f.readline() # seed sentence
	sentence = f.readline()
	encoded_drums = sentence.split(' ')

	#find the first BAR
	
	first_bar_idx = encoded_drums.index('BAR')
	
	encoded_drums = encoded_drums[first_bar_idx:]
	try:
		encoded_drums = [ele for ele in encoded_drums if ele not in ['BAR', 'SONG_BEGIN', 'SONG_END', '']]
	except:
		pdb.set_trace()

	# prepare output
	note_list = Note_List()
	pattern = midi.Pattern()
	track = midi.Track()
	#??
	PPQ = 220
	min_ppq = PPQ / (event_per_bar/4)
	track.resolution = PPQ
	pattern.append(track)

	velocity = 84
	duration = min_ppq*9/10  # it is easier to set new ticks if duration is shorter than _min_ppq

	note_list = text_to_notes(encoded_drums, note_list=note_list)
	
	max_c_tick = 0 
	not_yet_offed = [] # set of midi.pitch object 
	for note_idx, note in enumerate(note_list.notes[:-1]):
		# add onset
		tick_here = note.c_tick - max_c_tick
		pitch_here = pitch_to_midipitch[note.pitch]

		
		on = midi.NoteOnEvent(tick=tick_here, velocity=velocity, pitch=pitch_here, channel = 9)
		track.append(on)
		max_c_tick = max(max_c_tick, note.c_tick)

		# check out some note that not off-ed.
		for off_idx, waiting_pitch in enumerate(not_yet_offed):
			if off_idx == 0:
				off = midi.NoteOffEvent(tick=duration, pitch=waiting_pitch)
				max_c_tick = max_c_tick + duration
			else:
				off = midi.NoteOffEvent(tick=0, pitch=waiting_pitch)
			track.append(off)
			not_yet_offed = [] # set of midi.pitch object 

	# finalise
	if note_list.notes == []:
		print ('No notes in %s' % (filename))
		return
		pdb.set_trace()
	note = note_list.notes[-1]
	tick_here = note.c_tick - max_c_tick
	pitch_here = pitch_to_midipitch[note.pitch]
	on = midi.NoteOnEvent(tick=tick_here, velocity=velocity, pitch=pitch_here, channel = 9)
	off = midi.NoteOffEvent(tick=duration, pitch=pitch_here)

	for off_idx, waiting_pitch in enumerate(not_yet_offed):
		off = midi.NoteOffEvent(tick=0, pitch=waiting_pitch)

	# end of track event
	eot = midi.EndOfTrackEvent(tick=1)
	track.append(eot)
	midi.write_midifile(filename[:-4]+'.mid', pattern)
Ejemplo n.º 23
0
    # Append the track to the pattern
    pattern.append(track)
    # Instantiate a MIDI note on event, append it to the track
    on = midi.NoteOnEvent(tick=1000, velocity=100, pitch=i)
    track.append(on)
    # Instantiate a MIDI note off event, append it to the track
    off = midi.NoteOffEvent(tick=2000, pitch=i)
    track.append(off)

    on = midi.NoteOnEvent(tick=1000, velocity=100, pitch=i + 12)
    track.append(on)
    # Instantiate a MIDI note off event, append it to the track
    off = midi.NoteOffEvent(tick=2000, pitch=i + 12)
    track.append(off)
    # Add the end of track event, append it to the track
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    # Print out the pattern
    # Save the pattern to disk
    midi.write_midifile("example.mid", pattern)

    # t = madmom.utils.midi.MIDITrack(track)
    m = md.MIDIFile.from_file("example.mid")

    # t.events = [madmom.utils.midi.Event(e)]
    # m = madmom.utils.midi.MIDIFile([t])
    notes = m.notes()

    #convert notes to input vectors between 0 and 1
    vector = []
    vector.append(notes[0][0] / 7.29166667)
Ejemplo n.º 24
0
    def writemidi(self, filedir=""):
        # sorteer de events van abs ticks
        # gooit alle tracks en time signatures in track [0]

        # pak de track naam
        if self.texts[0][0].text != "":
            trackname = MIDI.TrackNameEvent(text=self.texts[0][0].text, tick=0)
            trackname.absoluteticks = 0
            # dunno werkt niet voor een of andere reden
            trackname.data = []
            i = 0
            while i < len(self.texts[0][0].text):
                trackname.data.append(ord(self.texts[0][0].text[i]))
                i += 1
            tracks = [[trackname]]
            del trackname  # verwijderd de naam als de hierboven genoteerde naam opnieuw wordt gebruikt
        else:
            tracks = [[]]
        # gooi alles in track [0]
        tracks[0] += self.texts[0][
            1:] + self.tempos + self.timesignatures + self.notes[0]
        # sorteer alles
        tracks[0].sort(key=operator.attrgetter('absoluteticks'))

        # pakt de instrument
        if self.channels[0] != 9 and self.instruments[0]:
            tracks[0].insert(
                0,
                MIDI.ProgramChangeEvent(value=self.instruments[0],
                                        channel=self.channels[0]))

        for i in range(1, len(self.notes)):
            # sorteer de tracks
            # pak de track naam
            if self.texts[i][0].text != "":
                trackname = MIDI.TrackNameEvent(text=self.texts[i][0].text,
                                                tick=0)
                # dunno dit werkt niet voor een of andere reden
                trackname.data = []
                trackname.absoluteticks = 0
                j = 0
                while j < len(self.texts[i][0].text):
                    trackname.data.append(ord(self.texts[i][0].text[j]))
                    j += 1
                tracks.append([trackname])
                del trackname  # verwijderd de naam als de hierboven genoteerde naam opnieuw wordt gebruikt
            else:
                tracks.append([])
            # pak de instrument
            tracks[i] += self.texts[i][1:] + self.notes[i]
            tracks[i].sort(key=operator.attrgetter('absoluteticks'))
            if self.channels[i] != 9 and self.instruments[i]:
                tracks[i].insert(
                    0,
                    MIDI.ProgramChangeEvent(value=self.instruments[i],
                                            channel=self.channels[i]))

        # kijk of de lokale ticks goed zijn
        tickdivisor = config.EDITresolution
        for i in range(len(tracks)):
            tracks[i].insert(
                0,
                MIDI.ControlChangeEvent(tick=0,
                                        channel=self.channels[i],
                                        data=[7, 127]))
        for track in tracks:
            previouseventabsoluteticks = 0
            for event in track:
                try:
                    thiseventabsoluteticks = int(event.absoluteticks)
                except AttributeError:
                    thiseventabsoluteticks = 0
                # aantal ticks in vergelijking tot voorgaande ticks en current ticks
                tickmeoff = thiseventabsoluteticks - previouseventabsoluteticks
                event.tick = tickmeoff
                # om te kijken hoe klein de resolutie is
                tickdivisor = gcd(tickdivisor, tickmeoff)
                # set de ticks voor de volgende event(midi)
                previouseventabsoluteticks = thiseventabsoluteticks

        if config.EDITresolution % tickdivisor:
            Error(
                " min RESOLUTON kan niet gedeeld worden door EDITresolution.  er is iets gaande "
            )

        newpattern = MIDI.Pattern(resolution=config.EDITresolution /
                                  tickdivisor)
        for track in tracks:
            if tickdivisor > 1:
                for event in track:
                    # deel de relatieve ticks
                    event.tick /= tickdivisor
                    # laat abs ticks in de edit resolution
            if track[-1].name != "End of Track":
                # voeg het einde van een track hier als het er niet is
                track.append(
                    MIDI.EndOfTrackEvent(tick=config.EDITresolution /
                                         tickdivisor))
            newpattern.append(MIDI.Track(track))

        if filedir == "":
            MIDI.write_midifile(self.midifile, newpattern)
        else:
            MIDI.write_midifile(filedir, newpattern)
Ejemplo n.º 25
0
import midi
pattern = midi.Pattern(resolution=480)
track = midi.Track()
pattern.append(track)

pattern2 = midi.read_midifile("example.mid")

print(pattern2)
pattern2[0][8] = midi.TimeSignatureEvent(tick=0, data=[4, 2, 24, 8])
pattern2[0][10] = midi.SetTempoEvent(tick=0, data=[12, 95])
pattern2[0][34] = midi.NoteOnEvent(tick=1, channel=0, data=[60, 61])
pattern2[0][35] = midi.NoteOnEvent(tick=120, channel=0, data=[64, 57])
pattern2[0][36] = midi.NoteOnEvent(tick=120, channel=0, data=[67, 56])
pattern2[0][37] = midi.NoteOnEvent(tick=120, channel=0, data=[67, 0])
pattern2[0][38] = midi.NoteOnEvent(tick=0, channel=0, data=[72, 60])
pattern2[0][39] = midi.SetTempoEvent(tick=119, data=[12, 32, 78])
pattern2[0][40] = midi.NoteOnEvent(tick=1, channel=0, data=[72, 0])
pattern2[0][41] = midi.NoteOnEvent(tick=0, channel=0, data=[76, 63])
pattern2[0][42] = midi.NoteOnEvent(tick=108, channel=0, data=[76, 0])
pattern2[0][43] = midi.SetTempoEvent(tick=11, data=[12, 95, 59])
pattern2[0][44] = midi.NoteOnEvent(tick=1, channel=0, data=[67, 50])
pattern2[0][45] = midi.NoteOnEvent(tick=120, channel=0, data=[67, 0])
pattern2[0][42] = midi.NoteOnEvent(tick=0, channel=0, data=[72, 47])
pattern2[0][42] = midi.NoteOnEvent(tick=120, channel=0, data=[72, 0])
pattern2[0][42] = midi.NoteOnEvent(tick=0, channel=0, data=[76, 47])
pattern2[0][42] = midi.NoteOnEvent(tick=120, channel=0, data=[76, 0])
pattern2[0][42] = midi.SetTempoEvent(tick=0, data=[12, 95])
print(pattern2[0][10])

pattern2[0].append(midi.EndOfTrackEvent(tick=0, data=[]))
midi.write_midifile("example2.mid", pattern2)
Ejemplo n.º 26
0
    def get_midi_pattern(self, song_data, bpm, normalized=True):
        """
        get_midi_pattern takes a song in internal representation
        (a tensor of dimensions [songlength, self.num_song_features]).
        the three values are length, frequency, velocity.
        if velocity of a frame is zero, no midi event will be
        triggered at that frame.

        returns the midi_pattern.

        Can be used with filename == None. Then nothing is saved, but only returned.
        """

        #
        # Interpreting the midi pattern.
        # A pattern has a list of tracks
        # (midi.Track()).
        # Each track is a list of events:
        #   * midi.events.SetTempoEvent: tick, data([int, int, int])
        #     (The three ints are really three bytes representing one integer.)
        #   * midi.events.TimeSignatureEvent: tick, data([int, int, int, int])
        #     (ignored)
        #   * midi.events.KeySignatureEvent: tick, data([int, int])
        #     (ignored)
        #   * midi.events.MarkerEvent: tick, text, data
        #   * midi.events.PortEvent: tick(int), data
        #   * midi.events.TrackNameEvent: tick(int), text(string), data([ints])
        #   * midi.events.ProgramChangeEvent: tick, channel, data
        #   * midi.events.ControlChangeEvent: tick, channel, data
        #   * midi.events.PitchWheelEvent: tick, data(two bytes, 14 bits)
        #
        #   * midi.events.NoteOnEvent:  tick(int), channel(int), data([int,int]))
        #     - data[0] is the note (0-127)
        #     - data[1] is the velocity.
        #     - if velocity is 0, this is equivalent of a midi.NoteOffEvent
        #   * midi.events.NoteOffEvent: tick(int), channel(int), data([int,int]))
        #
        #   * midi.events.EndOfTrackEvent: tick(int), data()
        #
        # Ticks are relative.
        #
        # Tempo are in microseconds/quarter note.
        #
        # This interpretation was done after reading
        # http://electronicmusic.wikia.com/wiki/Velocity
        # http://faydoc.tripod.com/formats/mid.htm
        # http://www.lastrayofhope.co.uk/2009/12/23/midi-delta-time-ticks-to-seconds/2/
        # and looking at some files. It will hopefully be enough
        # for the use in this project.
        #
        # This approach means that we do not currently support
        #   tempo change events.
        #

        # Tempo:
        # Multiply with output_ticks_pr_input_tick for output ticks.
        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=IDEAL_TEMPO))
        future_events = {}
        last_event_tick = 0

        ticks_to_this_tone = 0.0
        song_events_absolute_ticks = []
        abs_tick_note_beginning = 0.0

        if type(song_data) != np.ndarray:
            song_data = np.array(song_data)

        # de-normalize
        if normalized:
            de_norm_std(song_data, TICKS_FROM_PREV_START)
            de_norm_std(song_data, LENGTH)
            de_norm_std(song_data, VELOCITY)
            de_norm_minmax(song_data, TONE)

        for frame in song_data:
            abs_tick_note_beginning += int(round(frame[TICKS_FROM_PREV_START]))
            for subframe in range(self.tones_per_cell):
                offset = subframe * NUM_FEATURES_PER_TONE
                tick_len = int(round(frame[offset + LENGTH]))
                tone = int(round(frame[offset + TONE]))
                velocity = min(int(round(frame[offset + VELOCITY])), 127)

                if tone is not None and velocity > 0 and tick_len > 0:
                    # range-check with preserved tone, changed one octave:
                    while tone < 0:
                        tone += 12
                    while tone > 127:
                        tone -= 12

                    song_events_absolute_ticks.append(
                        (abs_tick_note_beginning,
                         midi.events.NoteOnEvent(tick=0,
                                                 velocity=velocity,
                                                 pitch=tone)))
                    song_events_absolute_ticks.append(
                        (abs_tick_note_beginning + tick_len,
                         midi.events.NoteOffEvent(tick=0,
                                                  velocity=0,
                                                  pitch=tone)))
        song_events_absolute_ticks.sort(key=lambda e: e[0])
        abs_tick_note_beginning = 0.0
        for abs_tick, event in song_events_absolute_ticks:
            rel_tick = abs_tick - abs_tick_note_beginning
            event.tick = int(round(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)

        return midi_pattern
Ejemplo n.º 27
0
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 12:56:08 2018

@author: wrb
"""

import numpy as np
import midi
import time

melody=np.loadtxt('save_test.txt',dtype=np.int32)

# Recon
tone_set=[midi.TimeSignatureEvent(tick=0, data=[4, 2, 24, 8]),
                             midi.EndOfTrackEvent(tick=0, data=[])]
note_list=[midi.ProgramChangeEvent(tick=0, channel=0, data=[1])]
l=np.shape(melody)[0]
k=0
p=0
#ch=np.array([[48,52,55],[43,47,50],[45,48,52],[40,43,47],
#             [41,45,48],[36,40,43],[38,41,45],[43,47,50]])+12
ch=np.array([[48,52,55],[47,50,55],[48,52,57],[47,52,55],
             [48,53,57],[48,52,55],[50,53,57],[47,50,55]])
amp1=112
amp0=80
rhy=80
for i in range(l):
    if (i%8==0):
        a=(i//8)%8
        if (i>0):
Ejemplo n.º 28
0
def midi_encode(note_seq, resolution=NOTES_PER_BEAT, step=1):
    """
    Takes a piano roll and encodes it into MIDI pattern
    """
    # Instantiate a MIDI Pattern (contains a list of tracks)
    pattern = midi.Pattern()
    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)

    play = note_seq[:, :, 0]
    replay = note_seq[:, :, 1]
    volume = note_seq[:, :, 2]

    # The current pattern being played
    current = np.zeros_like(play[0])
    # Absolute tick of last event
    last_event_tick = 0
    # Amount of NOOP ticks
    noop_ticks = 0

    for tick, data in enumerate(play):
        data = np.array(data)

        if not np.array_equal(current, data):  # or np.any(replay[tick]):
            noop_ticks = 0

            for index, next_volume in np.ndenumerate(data):
                if next_volume > 0 and current[index] == 0:
                    # Was off, but now turned on
                    evt = midi.NoteOnEvent(
                        tick=(tick - last_event_tick) * step,
                        velocity=int(volume[tick][index[0]] * MAX_VELOCITY),
                        pitch=index[0])
                    track.append(evt)
                    last_event_tick = tick
                elif current[index] > 0 and next_volume == 0:
                    # Was on, but now turned off
                    evt = midi.NoteOffEvent(tick=(tick - last_event_tick) *
                                            step,
                                            pitch=index[0])
                    track.append(evt)
                    last_event_tick = tick

                elif current[index] > 0 and next_volume > 0 and replay[tick][
                        index[0]] > 0:
                    # Handle replay
                    evt_off = midi.NoteOffEvent(tick=(tick - last_event_tick) *
                                                step,
                                                pitch=index[0])
                    track.append(evt_off)
                    evt_on = midi.NoteOnEvent(
                        tick=0,
                        velocity=int(volume[tick][index[0]] * MAX_VELOCITY),
                        pitch=index[0])
                    track.append(evt_on)
                    last_event_tick = tick

        else:
            noop_ticks += 1

        current = data

    tick += 1

    # Turn off all remaining on notes
    for index, vol in np.ndenumerate(current):
        if vol > 0:
            # Was on, but now turned off
            evt = midi.NoteOffEvent(tick=(tick - last_event_tick) * step,
                                    pitch=index[0])
            track.append(evt)
            last_event_tick = tick
            noop_ticks = 0

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

    return pattern
Ejemplo n.º 29
0
def write_solution(one_sol,
                   num_bars,
                   solution_file,
                   cp_chord=False,
                   cf_chord=True,
                   random_length=True):
    cp_pitches = []
    cf_pitches = []

    one_sol[1].domain[0].getPitch()
    for i in range(len(one_sol)):
        if i % 2 == 0:  # Note is from counterpoint
            base = one_sol[i].domain[0].getPitch()
            if cp_chord:
                cp_pitches.append([base, base + 4, base + 7])
            else:
                cp_pitches.append(
                    [one_sol[i].domain[0].getPitch() + OCTAVE * 2])
        else:  # Note is from the cantus firmus
            base = one_sol[i].domain[0].getPitch()
            if cf_chord:
                if i == num_bars * 2 - 3:
                    cf_pitches.append([base, base - 4, base - 7, base - 12])
                else:
                    cf_pitches.append([base, base - 3, base - 7, base - 12])
            else:
                cf_pitches.append([base])
    # Helper function to add a note to a track
    def append_note(track, pitch, velocity=70):
        on = midi.NoteOnEvent(tick=0, velocity=velocity, pitch=pitch)
        track.append(on)
        off = midi.NoteOffEvent(tick=180, pitch=pitch)
        track.append(off)

    # Initialize MIDI variables
    pattern = midi.Pattern()
    track_cf = midi.Track()
    track_cp = midi.Track()
    pattern.append(track_cf)
    pattern.append(track_cp)

    notelengths = [60, 120, 180, 240]

    # Add all cantus firmus and counterpoint pitches to the track
    for i in range(num_bars):
        if random_length:
            length = random.choice(notelengths)
        else:
            length = 180
        for pitch in cf_pitches[i]:
            # Keep notes in the same chord at the same point
            on = midi.NoteOnEvent(tick=0, velocity=60, pitch=pitch)
            track_cf.append(on)
        off = midi.NoteOffEvent(tick=length, pitch=cf_pitches[i][0])
        track_cf.append(off)
        for pitch in cf_pitches[i][1:]:
            off = midi.NoteOffEvent(tick=0, pitch=pitch)
            track_cf.append(off)
        for pitch in cp_pitches[i]:
            on = midi.NoteOnEvent(tick=0, velocity=60, pitch=pitch)
            track_cp.append(on)
        off = midi.NoteOffEvent(tick=length, pitch=cp_pitches[i][0])
        track_cp.append(off)
        for pitch in cp_pitches[i][1:]:
            off = midi.NoteOffEvent(tick=0, pitch=pitch)
            track_cp.append(off)
        #cp_pitch = cp_pitches[i]
        #append_note(track_cp, cp_pitch, 60)
    eot = midi.EndOfTrackEvent(tick=1)
    track_cp.append(eot)
    track_cf.append(eot)

    midi.write_midifile(solution_file, pattern)

    #print('\nCantus firmus midi: ' + cantus_file)
    print('Solution midi: ' + solution_file)
def notePlayMatrixToMidi(NotePlayMatrix, name = "example"):
    pattern = midi.Pattern()
    pattern.resolution = 480
    main_track = midi.Track()
    drum_track = midi.Track()
    pattern.append(main_track)
    pattern.append(drum_track)

    main_ticks_count= note_res
    drum_ticks_count= note_res
    print(NotePlayMatrix.shape[0])
    for pos in range(NotePlayMatrix.shape[0]):
        if pos == 0:
            notes = np.nonzero(NotePlayMatrix[0,:])[0]
            for n in notes:
                if n < span_main + 1:
                    main_track.append(midi.NoteOnEvent(tick=0, velocity=40,
                     pitch=n+lowerBound_main))
                else:
                    drum_track.append(midi.NoteOnEvent(tick=0, velocity=40,
                     pitch=n-span_main-1+lowerBound_drum))

        else:
            noteChanges = NotePlayMatrix[pos,:] != NotePlayMatrix[pos-1,:]

            #main track
            if sum(noteChanges[:span_main+1]) == 0 :
                main_ticks_count = main_ticks_count + note_res
            else:
                notes = np.where(noteChanges[:span_main+1])[0]
                notes_status = NotePlayMatrix[pos,:span_main+1][noteChanges[:span_main+1]]

                for n in range(len(notes)):
                    if notes_status[n] == 1:
                        main_track.append(midi.NoteOnEvent(tick=main_ticks_count, velocity=40,
                        pitch=notes[n]+lowerBound_main))
                    if notes_status[n] == 0:
                        main_track.append(midi.NoteOffEvent(tick=main_ticks_count,
                        pitch=notes[n]+lowerBound_main))
                    main_ticks_count = 0

                main_ticks_count= note_res

            # drum track
            if sum(noteChanges[span_main+1:]) == 0:
                drum_ticks_count = drum_ticks_count + note_res
            else:
                notes = np.where(noteChanges[span_main+1:])[0]
                notes_status = NotePlayMatrix[pos,span_main+1:][noteChanges[span_main+1:]]

                for n in range(len(notes)):
                    if notes_status[n] == 1:
                        drum_track.append(midi.NoteOnEvent(tick=drum_ticks_count, velocity=40,
                        pitch=notes[n] + lowerBound_drum))
                    if notes_status[n] == 0:
                        drum_track.append(midi.NoteOffEvent(tick=drum_ticks_count,
                        pitch=notes[n] + lowerBound_drum))

                    drum_ticks_count = 0

                drum_ticks_count= note_res


    eot = midi.EndOfTrackEvent(tick=0)
    main_track.append(eot)
    drum_track.append(eot)

#    print(np.sum(NotePlayMatrix,axis = 1))

    midi.write_midifile("{}.mid".format(name), pattern)