コード例 #1
0
ファイル: track_util.py プロジェクト: FrendoWu/beats2beats
def _set_time_signature(track, data):
    """
    设置一个自己写的Track的time signature
    """
    TimeSignatureEvent = midi.TimeSignatureEvent(data=data)
    track.insert(0, TimeSignatureEvent)
    return track
コード例 #2
0
ファイル: sequences.py プロジェクト: aolsenjazz/cybach
    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
コード例 #3
0
def finalize_midi_sequence(ptrn,
                           name="Track 1",
                           inst=0,
                           channel=0,
                           tsig=(4, 4),
                           bpm=120):
    """
    Makes a geenrated midi sequnce valid for most players 
    by adding TimeSignature, SetTempo and EndOfTrack events.
    """
    has_tsig = False
    has_tempo = False
    has_end = False
    for evnt in utils.evnt_gen(ptrn):
        if isinstance(evnt, midi.SetTempoEvent):
            has_tsig = True
        if isinstance(evnt, midi.TimeSignatureEvent):
            has_tempo = True
        if isinstance(evnt, midi.EndOfTrackEvent):
            has_end = True
    if not has_tsig:
        ptrn[0].insert(0, midi.TimeSignatureEvent(tick=0))
        ptrn[0][0].data[:2] = tsig
        ptrn[0][0].data[2:] = 24, 8
    if not has_tempo:
        ptrn[0].insert(0, midi.SetTempoEvent(tick=0))
        ptrn[0][0].set_bpm(bpm)
    if not has_end:
        ptrn[0].append(midi.EndOfTrackEvent(tick=0))
    ptrn[0].insert(0, midi.TrackNameEvent(tick=0, text=name, data=[]))
    ptrn[0].insert(
        0, midi.ProgramChangeEvent(tick=0, channel=channel, data=[inst]))
    return ptrn
コード例 #4
0
def numpy2midi(X, midifile, bpm=155):
    # pad to fill last bar (we fill to 16th)
    padded_dim = -16 * (
        -X.shape[0] // 16
    )  # remainder of negative numbers equals to ceil() instead of floor()
    X_padded = np.zeros((padded_dim, X.shape[1]), dtype=int)
    X_padded[:X.shape[0], :X.shape[1]] = X
    X = X_padded

    # find for each timestep the set of on-notes
    X = [set(np.nonzero(x)[0]) for x in X]

    # prepend and append an empty step to the song
    X.insert(0, set())
    X.append(set())

    conductor = midi.Track()
    time_sig = midi.TimeSignatureEvent(tick=0,
                                       numerator=4,
                                       denominator=4,
                                       metronome=24,
                                       thirtyseconds=8)
    conductor.append(time_sig)
    tempo = midi.SetTempoEvent(tick=0, bpm=bpm)
    conductor.append(tempo)

    track = midi.Track()

    tick = 0
    for previous, current in zip(X[:-1], X[1:]):
        notes_to_off = previous - current  # notes in the previous but not in the current (ending notes)
        for pitch in map(_index2pitch, notes_to_off):
            off = midi.NoteOffEvent(
                tick=tick, pitch=pitch,
                velocity=0)  # velocity is ignored in NoteOffEvents
            track.append(off)
            tick = 0

        notes_to_on = current - previous  # notes in the current but not in the previous (beginning notes)
        for pitch in map(_index2pitch, notes_to_on):
            on = midi.NoteOnEvent(tick=tick, pitch=pitch, velocity=100)
            track.append(on)
            tick = 0

        tick += 1

    # end of track event
    eot = midi.EndOfTrackEvent(tick=0)
    conductor.append(eot)
    track.append(eot)

    # instantiate a MIDI Pattern (contains a list of tracks)
    pattern = midi.Pattern(resolution=4)
    # append the track to the pattern
    pattern.append(conductor)
    pattern.append(track)
    # save the pattern to disk
    midi.write_midifile(midifile, pattern)
コード例 #5
0
ファイル: midi_skirt.py プロジェクト: jwnorman/midi-skirt
 def _initialize_or_reset_state(self):
     self.track_uuid = str(uuid.uuid4())[0:7]
     self.pattern = midi.Pattern(resolution=self.pc.resolution)
     self.track = midi.Track()
     self.pattern.append(self.track)
     self.track.append(midi.SetTempoEvent(bpm=self.bpm))
     self.track.append(
         midi.TimeSignatureEvent(
             numerator=self.time_signature_numerator,
             denominator=self.time_signature_denominator))
コード例 #6
0
ファイル: fileloader.py プロジェクト: aolsenjazz/cybach
def __init_time_signature_entry(sequence):
    if time.__signatures:
        __report_time_signature_data()
        __manual_delete_time_signatures()

    enter = 'y'
    while enter == 'y':
        enter = raw_input('Would you like to insert a time signature? y/n ')

        if enter == 'y':
            numerator = int(raw_input('Signature numerator: '))
            denominator = int(raw_input('Signature denominator: '))
            measure = int(raw_input('Measure: '))

            event = midi.TimeSignatureEvent(
                data=[numerator, denominator, 36, 8])
            time.__signatures[sequence.measure(measure - 1).start()] = event
コード例 #7
0
def generate_composition(number_of_tracks):
    head_of_file = []
    pattern = midi.Pattern()
    t = midi.Track()

    note_choices = [2, 4, 8, 16]
    note_durations = []
    for i in range(0, 54):
        note_durations.append(random.choice(note_choices))

    for i in range(0, number_of_tracks):
        counter = 0
        s = midi.read_midifile("theme_and_variations-{0}.midi".format(i))
        for note in s[1][1:-1]:
            note.tick = note_durations[counter]
            counter += 1
        midi.write_midifile("theme_and_variations-{0}.midi".format(i), s)

    for i in range(0, number_of_tracks):
        s = midi.read_midifile("theme_and_variations-{0}.midi".format(i))
        if i == 0:
            head_of_file = s[0]
            del head_of_file[-1]
            head_of_file[2] = midi.SetTempoEvent(tick=0, data=[11, 113, 176])
            head_of_file[0] = midi.TimeSignatureEvent(tick=0,
                                                      data=[4, 2, 96, 8])
            del s[1][-1]
            t.extend(s[1])
        elif i == number_of_tracks - 1:
            del s[1][0]
            t.extend(s[1])
        else:
            del s[1][-1]
            del s[1][0]
            t.extend(s[1])
        os.remove("theme_and_variations-{0}.midi".format(i))
    pattern.resolution = 32
    pattern.format = 1
    pattern.append(head_of_file)
    pattern.append(t)
    print pattern

    # Make file and move it to download directory to present to user
    midi.write_midifile("Theme-And-Variations.midi", pattern)
    print " DONE! "
コード例 #8
0
    def addtimesignatureevent(self, num=4, absoluteticks=0):
        ts = MIDI.TimeSignatureEvent(numerator=num)
        ts.absoluteticks = absoluteticks

        if len(self.timesignatures):
            if absoluteticks > self.timesignatures[-1].absoluteticks:
                self.timesignatures.append(ts)
            else:
                i = 0
                while i < len(self.timesignatures):
                    if absoluteticks < self.timesignatures[i].absoluteticks:
                        self.timesignatures.insert(i, ts)
                        break
                    elif absoluteticks == self.timesignatures[i].absoluteticks:
                        self.timesignatures[i] = ts
                        break
                    else:
                        i += 1
        else:
            self.timesignatures.append(ts)
コード例 #9
0
ファイル: piece.py プロジェクト: williamjoy/pyanoh3ro
    def addtimesignatureevent( self, num=4, absoluteticks=0 ):
        ts = MIDI.TimeSignatureEvent( numerator=num )
        ts.absoluteticks = absoluteticks

        if len(self.timesignatures):
            # if it's at the end of things
            if absoluteticks > self.timesignatures[-1].absoluteticks:
                self.timesignatures.append( ts )
            else: 
                # otherwise it's somewhere in the middle
                i = 0
                while i < len(self.timesignatures):
                    if absoluteticks < self.timesignatures[i].absoluteticks:
                        self.timesignatures.insert(i, ts)
                        break
                    elif absoluteticks == self.timesignatures[i].absoluteticks:
                        self.timesignatures[i] = ts
                        break
                    else:
                        i += 1
        else:
            self.timesignatures.append( ts )
コード例 #10
0
ファイル: timeline.py プロジェクト: gesellkammer/maelzel
    def write_midi(self, midifile, resolution=1920, fillpitch=60):
        """
        Discards any tempo transition, assumes the tempo at the beginning of the measure
        stays the same for the entire measure

        midifile: path of the midi file
        resolution: the ticks per second
        fillpitch: the pitch to be used to fill each measure
        """
        import midi
        t = midi.Track()
        t.tick_relative = False
        sec2tick = lambda sec: int(sec * resolution)
        tempo = -1
        now = 0
        for i, measure in enumerate(self.measures):
            beat = self.index.measure2beat(i)
            assert (now - beat) < 0.0001, \
                "now: {}, beat: {}, timesig: {}, prev: {}".format(
                    now, beat, measure.timesig, self.measures[i - 1])
            temponow = int(self.tempocurve(beat))
            durbeats = measure.numbeats
            t.append(midi.TimeSignatureEvent(tick=sec2tick(now), 
                                             numerator=measure.num,
                                             denominator=measure.den))
            if temponow != tempo:
                tempo = temponow
                t.append(midi.SetTempoEvent(tick=sec2tick(now), bpm=tempo))
            t.append(midi.NoteOnEvent(tick=sec2tick(now),
                                      pitch=fillpitch, velocity=1))
            t.append(midi.NoteOffEvent(tick=sec2tick(now + durbeats), 
                                       pitch=fillpitch, velocity=0))
            now += durbeats
        t.append(midi.EndOfTrackEvent(tick=sec2tick(now) + 1))
        midipattern = midi.Pattern([t], resolution=resolution)
        midipattern.tick_relative = False
        midipattern.make_ticks_rel()
        midi.write_midifile(midifile, midipattern)
        return midipattern
コード例 #11
0
ファイル: midi_export.py プロジェクト: zuzazapata/watson
import midi
# Instantiate a MIDI Pattern (contains a list of tracks)
pattern = midi.Pattern(format=0, resolution=480)
# Instantiate a MIDI Track (contains a list of MIDI events)
track = midi.Track()
# Append the track to the pattern
pattern.append(track)
# Midi Events Start Here
# Instantiate a MIDI note on event, append it to the track

time = midi.TimeSignatureEvent(tick=0, data=[4, 2, 24, 8])
track.append(time)
on = midi.NoteOnEvent(tick=0, velocity=83, pitch=midi.C_5)
track.append(on)
off = midi.NoteOffEvent(tick=132, velocity=0, pitch=midi.C_5)
track.append(off)
on = midi.NoteOnEvent(tick=588, velocity=55, pitch=midi.F_4)
track.append(on)
off = midi.NoteOffEvent(tick=63, velocity=0, pitch=midi.F_4)
track.append(off)
on = midi.NoteOnEvent(tick=177, velocity=60, pitch=midi.Gs_4)
track.append(on)
off = midi.NoteOffEvent(tick=426, velocity=0, pitch=midi.Gs_4)
track.append(off)
on = midi.NoteOnEvent(tick=294, velocity=55, pitch=midi.As_4)
track.append(on)
off = midi.NoteOffEvent(tick=99, velocity=0, pitch=midi.As_4)
track.append(off)
on = midi.NoteOnEvent(tick=141, velocity=67, pitch=midi.C_5)
track.append(on)
off = midi.NoteOffEvent(tick=131, velocity=0, pitch=midi.C_5)
コード例 #12
0
    def dump_sequence_to_midi(self,
                              sequence,
                              output_filename,
                              time_step,
                              resolution,
                              metronome=24):
        if self.verbose:
            print "Dumping sequence to MIDI file: {}".format(output_filename)
            print "Resolution: {}".format(resolution)
            print "Time Step: {}".format(time_step)

        pattern = midi.Pattern(resolution=resolution)
        self.track = midi.Track()

        # metadata track
        meta_track = midi.Track()
        time_sig = midi.TimeSignatureEvent()
        time_sig.set_numerator(4)
        time_sig.set_denominator(4)
        time_sig.set_metronome(metronome)
        time_sig.set_thirtyseconds(8)
        meta_track.append(time_sig)
        pattern.append(meta_track)

        # reshape to (SEQ_LENGTH X NUM_DIMS)
        sequence = np.reshape(sequence, [-1, self.note_range])

        time_steps = sequence.shape[0]
        if self.verbose:
            print "Total number of time steps: {}".format(time_steps)

        tick = time_step
        self.notes_on = {n: False for n in range(self.note_range)}
        # for seq_idx in range(188, 220):
        for seq_idx in range(time_steps):
            notes = np.nonzero(sequence[seq_idx, :])[0].tolist()

            # this tick will only be assigned to first NoteOn/NoteOff in
            # this time_step

            # NoteOffEvents come first so they'll have the tick value
            # go through all notes that are currently on and see if any
            # turned off
            for n in self.notes_on:
                if self.notes_on[n] and n not in notes:
                    tick = self.note_off(n, tick)
                    self.notes_on[n] = False

            # Turn on any notes that weren't previously on
            for note in notes:
                if not self.notes_on[note]:
                    tick = self.note_on(note, tick)
                    self.notes_on[note] = True

            tick += time_step

        # flush out notes
        for n in self.notes_on:
            if self.notes_on[n]:
                self.note_off(n, tick)
                tick = 0
                self.notes_on[n] = False

        pattern.append(self.track)
        midi.write_midifile(output_filename, pattern)
コード例 #13
0
ファイル: GSIO.py プロジェクト: GiantSteps/GS_API
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
コード例 #14
0
ファイル: mary_test.py プロジェクト: waykole/python-midi
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]),
  midi.NoteOnEvent(tick=0, channel=0, data=[64, 0]),
  midi.NoteOnEvent(tick=50, channel=0, data=[62, 75]),
  midi.NoteOnEvent(tick=0, channel=0, data=[55, 77]),
  midi.NoteOnEvent(tick=231, channel=0, data=[62, 0]),
コード例 #15
0
    def dump_sequence_to_midi(self, seq, output_filename,
        time_step=120, resolution=480, metronome=24, offset=21,
        format='final'):
        if self.verbose:
            print "Dumping sequence to MIDI file: {}".format(output_filename)
            print "Resolution: {}".format(resolution)
            print "Time Step: {}".format(time_step)

        pattern = midi.Pattern(resolution=resolution)
        self.track = midi.Track()

        # metadata track
        meta_track = midi.Track()
        time_sig = midi.TimeSignatureEvent()
        time_sig.set_numerator(4)
        time_sig.set_denominator(4)
        time_sig.set_metronome(metronome)
        time_sig.set_thirtyseconds(8)
        meta_track.append(time_sig)
        pattern.append(meta_track)

        # reshape to (SEQ_LENGTH X NUM_DIMS)
        if format == 'icml':
            # assumes seq is list of lists, where each inner list are all the midi notes that were non-zero at that given timestep
            sequence = np.zeros([len(seq), self.note_range])
            sequence = [1 if i in tmstp else 0 for i in xrange(self.note_range) for tmstp in seq]
            sequence = np.reshape(sequence, [self.note_range,-1]).T
        elif format == 'flat':
            sequence = np.reshape(seq, [-1, self.note_range])
        else:
            sequence = seq

        time_steps = sequence.shape[0]
        if self.verbose:
            print "Total number of time steps: {}".format(time_steps)

        tick = time_step
        self.notes_on = { n: False for n in range(self.note_range) }
        # for seq_idx in range(188, 220):
        for seq_idx in range(time_steps):
            notes = np.nonzero(sequence[seq_idx, :])[0].tolist()
            # n.b. notes += 21 ??
            # need to be in range 21,109
            notes = [n+offset for n in notes]

            # this tick will only be assigned to first NoteOn/NoteOff in
            # this time_step

            # NoteOffEvents come first so they'll have the tick value
            # go through all notes that are currently on and see if any
            # turned off
            for n in self.notes_on:
                if self.notes_on[n] and n not in notes:
                    tick = self.note_off(n, tick)
                    self.notes_on[n] = False

            # Turn on any notes that weren't previously on
            for note in notes:
                if not self.notes_on[note]:
                    tick = self.note_on(note, tick)
                    self.notes_on[note] = True

            tick += time_step

        # flush out notes
        for n in self.notes_on:
            if self.notes_on[n]:
                self.note_off(n, tick)
                tick = 0
                self.notes_on[n] = False

        pattern.append(self.track)
        midi.write_midifile(output_filename, pattern)
コード例 #16
0
ファイル: midi2numpy.py プロジェクト: jmmcd/drum-manifold
def numpy2midi(n):
    """Convert a numpy array n to a midi pattern in python-midi
    format, quantised etc."""
    # print(n)
    # print(n.shape)
    resolution = 4
    p = midi.Pattern(resolution=resolution)  #, tick_relative=False)

    track = midi.Track()
    #track = midi.Track(tick_relative=False)

    p.append(track)

    set_tempo = midi.SetTempoEvent()
    set_tempo.set_bpm(120)
    set_tempo.set_mpqn(120)
    track_name = midi.TrackNameEvent(trackname="Track name")
    time_sig = midi.TimeSignatureEvent()
    time_sig.set_numerator(4)
    time_sig.set_denominator(4)
    time_sig.set_metronome(180)
    # time_sig.set_thirtyseconds(32)

    end = midi.EndOfTrackEvent()
    end.tick = nsteps * resolution

    #track.append(set_tempo)
    #track.append(track_name)
    #track.append(time_sig)

    for step in range(nsteps):
        tick = 0
        for drum in range(len(names)):
            # print(n[drum, step])
            if n[drum, step] > 0:
                on = midi.NoteOnEvent()
                on.channel = 9
                on.pitch = dm2[drum]
                on.velocity = int(n[drum, step])
                on.tick = tick
                track.append(on)
                # print(on)
            tick = 0

        tick = resolution
        for drum in range(len(names)):
            if True:
                #elif step > 0 and n[drum, step-1] > 0:
                off = midi.NoteOffEvent()
                off.channel = 9
                off.pitch = dm2[drum]
                off.velocity = 100
                off.tick = tick
                track.append(off)
                # print(off)
            tick = 0

    track.append(end)

    #p.make_ticks_rel()

    return p
コード例 #17
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):
コード例 #18
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)
コード例 #19
0
def change_music_to_pattern(music):
    music.parse_track_msg()
    # music._init_main_trank()

    pattern = midi.Pattern()
    pattern.resolution = music.get_resolution()
    pattern.format = music.get_play_format()
    for track in reversed(music.track):
        t = midi.Track()
        for event in track:
            event_tick = int(event[0])
            event_event = event[1]
            state_code = event_event["state_code"]
            if state_code == 255:
                if event_event["name"] == 'Set Tempo':
                    eve = midi.SetTempoEvent(tick=event_tick,
                                             bpm=event_event["bpm"])
                elif event_event["name"] == 'Trank Name':
                    eve = midi.TrackNameEvent(tick=event_tick,
                                              text=event_event["text"])
                elif event_event["name"] == 'Copyright Notice':
                    eve = midi.CopyrightMetaEvent(tick=event_tick,
                                                  text=event_event["text"])
                elif event_event["name"] == 'SMPTE Offset':
                    eve = midi.SmpteOffsetEvent(tick=event_tick,
                                                text=event_event["text"])
                elif event_event["name"] == 'Time Signature':
                    eve = midi.TimeSignatureEvent(
                        tick=event_tick,
                        numerator=event_event["numerator"],
                        denominator=event_event["denominator"],
                        metronome=event_event["metronome"],
                        thirtyseconds=event_event["thirtyseconds"])
                elif event_event["name"] == "End of Track":
                    eve = midi.EndOfTrackEvent(tick=event_tick)
                else:
                    continue
            elif 240 <= state_code <= 254:
                # 系统码
                eve = midi.SysexEvent()
            elif 224 <= state_code <= 239:
                # 滑音
                eve = midi.PitchWheelEvent(tick=event_tick,
                                           channel=event_event["channel"],
                                           pitch=event_event["pitch"])
            elif 208 <= state_code <= 223:
                # After Touch
                eve = midi.AfterTouchEvent()
            elif 192 <= state_code <= 207:
                # 乐器转换
                eve = midi.ProgramChangeEvent(tick=event_tick,
                                              channel=event_event["channel"],
                                              data=[event_event["program"]])
            elif 176 <= state_code <= 191:
                # midi控制器
                eve = midi.ControlChangeEvent(
                    tick=event_tick,
                    channel=event_event["channel"],
                    data=[event_event["control"], event_event["value"]])
            elif 160 <= state_code <= 175:
                continue
            elif 144 <= state_code <= 159:
                # note on
                eve = midi.NoteOnEvent(tick=event_tick,
                                       channel=event_event["channel"],
                                       velocity=event_event["velocity"],
                                       pitch=event_event["pitch"])
            elif 128 <= state_code <= 143:
                # note off
                eve = midi.NoteOffEvent(tick=event_tick,
                                        channel=event_event["channel"],
                                        velocity=event_event["velocity"],
                                        pitch=event_event["pitch"])
            elif state_code <= 127:
                continue

            t.append(eve)
        pattern.append(t)
    return pattern
コード例 #20
0
# load file
pattern = midi.read_midifile(filename)

# list for new note items
new_notes = []

# magic number for resolution of hydrogen files
res = 48

# number of beats per quarter note in midi file
resolution = pattern.resolution

note = midi.NoteOnEvent()
noteoff = midi.NoteOffEvent()
timeSig = midi.TimeSignatureEvent()
tempo = midi.SetTempoEvent()

# number of beats per quarter in midi file / number of beats per quater in hydrogen
ratio = resolution / res

# get length from total number of ticks
total_ticks = 0
for track in pattern:
    this_track_ticks = 0
    for line in track:
        if type(line) == type(timeSig):
            timeSig = line
        elif type(line) == type(tempo):
            tempo = line
        elif type(line) == type(note):