示例#1
0
 def arpeggiator(chord, start, track):
     for i in range(2):
         on = midi.NoteOnEvent(tick=0,
                               velocity=80,
                               pitch=midi.C_4 + chord.tones[0])
         off = midi.NoteOffEvent(tick=110, pitch=midi.C_4 + chord.tones[0])
         track.append(on)
         track.append(off)
         on = midi.NoteOnEvent(tick=0,
                               velocity=80,
                               pitch=midi.C_4 + chord.tones[1])
         off = midi.NoteOffEvent(tick=110, pitch=midi.C_4 + chord.tones[1])
         track.append(on)
         track.append(off)
         on = midi.NoteOnEvent(tick=0,
                               velocity=80,
                               pitch=midi.C_4 + chord.tones[2])
         off = midi.NoteOffEvent(tick=110, pitch=midi.C_4 + chord.tones[2])
         track.append(on)
         track.append(off)
         on = midi.NoteOnEvent(tick=0,
                               velocity=80,
                               pitch=midi.C_4 + chord.tones[1])
         off = midi.NoteOffEvent(tick=110, pitch=midi.C_4 + chord.tones[1])
         track.append(on)
         track.append(off)
示例#2
0
def get_13(pitch, pitch1):
    on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch)
    off = midi.NoteOffEvent(tick=100, pitch=pitch1)
    track.extend([on, off])
    on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch1)
    off = midi.NoteOffEvent(tick=300, pitch=pitch)
    track.extend([on, off])
示例#3
0
    def on_frame(self, controller):
        # Get the most recent frame and report some basic information
        frame = controller.frame()
        previous_frame = controller.frame(1)
        last_frame = controller.frame(10)
        back_frame = controller.frame(20)

        #print "Frame id: %d, timestamp: %d, hands: %d, fingers: %d, tools: %d, gestures: %d" % (
        #      frame.id, frame.timestamp, len(frame.hands), len(frame.fingers), len(frame.tools), len(frame.gestures()))

        # direction of index finger
        direction_1 = frame.hands.rightmost.fingers[1].bone(2).direction
        direction_2 = last_frame.hands.rightmost.fingers[1].bone(2).direction
        direction_3 = back_frame.hands.rightmost.fingers[1].bone(2).direction

        middle_1 = frame.hands.rightmost.fingers[2].bone(2).direction
        middle_2 = last_frame.hands.rightmost.fingers[2].bone(2).direction
        middle_3 = back_frame.hands.rightmost.fingers[2].bone(2).direction

        # angle of these two finger vector
        if (direction_1).angle_to(direction_2) > np.pi / 9 and (
                direction_1).angle_to(direction_3) < np.pi / 15:
            print "index finger press action, direction vector: ", direction_1, direction_2, direction_3
            # tick of midi is milli second 1e-3second, timestamp of frame is micro second 1e-6second
            #start_ = int((frame.timestamp - self.first_timestamp)/ 1000.0)
            self.track.append(
                midi.NoteOnEvent(tick=50, velocity=50, pitch=midi.G_3))
            self.track.append(
                midi.NoteOffEvent(tick=150, velocity=50, pitch=midi.G_3))

        if (middle_1).angle_to(middle_2) > np.pi / 10 and (
                middle_1).angle_to(middle_3) < np.pi / 15:
            print "index finger press action, direction vector: ", middle_1, middle_2, middle_3
            # tick of midi is milli second 1e-3second, timestamp of frame is micro second 1e-6second
            #start_ = int((frame.timestamp - self.first_timestamp)/ 1000.0)
            self.track.append(
                midi.NoteOnEvent(tick=50, velocity=50, pitch=midi.A_3))
            self.track.append(
                midi.NoteOffEvent(tick=150, velocity=50, pitch=midi.A_3))

        # get the normal vector of the palm
        normal = frame.hands.rightmost.palm_normal
        previous_normal = previous_frame.hands.rightmost.palm_normal

        print normal[0], normal[1], normal[2]

        # stop is the palm normal is inversed
        if previous_normal[2] * normal[2] < 0:
            # end the track, add it to the pattern
            print "end track event, track adds to pattern"
            self.track.append(midi.EndOfTrackEvent(tick=1))
            self.pattern.append(self.track)
            # write pattern to file midi
            print "write pattern to file: "
            midi.write_midifile("example.mid", self.pattern)

            # stop the listener
            print "stop"
            controller.remove_listener(self)
示例#4
0
def final(chords, path):
    pattern = midi.read_midifile(path)
    track = pattern[0]
    l = len(track)

    chord_counter = 0

    num_notes = []

    for i in range(l):
        if isinstance(track[i], midi.NoteOnEvent):
            num_notes.append(i)

    i = 0
    for index in num_notes:
        event1 = midi.NoteOnEvent(tick=0,
                                  channel=0,
                                  data=[chords[chord_counter][0], 60])
        event2 = midi.NoteOnEvent(tick=0,
                                  channel=0,
                                  data=[chords[chord_counter][1], 60])
        event3 = midi.NoteOnEvent(tick=0,
                                  channel=0,
                                  data=[chords[chord_counter][2], 60])
        track.insert(index + 1 + i, event1)
        track.insert(index + 2 + i, event2)
        track.insert(index + 3 + i, event3)
        i += 3

        chord_counter += 1

    off_indices = []
    for i in range(len(track)):
        if isinstance(track[i], midi.NoteOffEvent):
            off_indices.append(i)

    chord_counter = 0
    i = 0
    for index in off_indices:
        event1 = midi.NoteOffEvent(tick=0,
                                   channel=0,
                                   data=[chords[chord_counter][0], 60])
        event2 = midi.NoteOffEvent(tick=0,
                                   channel=0,
                                   data=[chords[chord_counter][1], 60])
        event3 = midi.NoteOffEvent(tick=0,
                                   channel=0,
                                   data=[chords[chord_counter][2], 60])
        track.insert(index + 1 + i, event1)
        track.insert(index + 2 + i, event2)
        track.insert(index + 3 + i, event3)
        i += 3

        chord_counter += 1
    '''track.insert(7, midi.NoteOnEvent(tick=0, channel=0, data=[36, 90]))'''
    print("writing pattern to harmoni.mid")
    # print("pattern is ", pattern)
    midi.write_midifile("harmoni.mid", pattern)
def build_midi_pattern(note_matrix, midi_ticks_per_step=50):
    print('Building MIDI pattern from note matrix...')
    note_matrix = trim_note_matrix(note_matrix)

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

    tick_distance = 0
    previous_time_step = np.zeros(MAX_MIDI_PITCH)

    for cur_time_step in note_matrix.T:
        for midi_pitch in range(MAX_MIDI_PITCH):
            note_type = cur_time_step[midi_pitch]

            # no track event
            if note_type == 2 or (note_type == 0
                                  and previous_time_step[midi_pitch] == 0):
                continue

            elif note_type == 0:
                off = midi.NoteOffEvent(tick=tick_distance + 2,
                                        pitch=midi_pitch)
                track.append(off)
                tick_distance = 0
                continue

            elif previous_time_step[midi_pitch] != 0:
                off = midi.NoteOffEvent(tick=tick_distance, pitch=midi_pitch)
                track.append(off)
                tick_distance = 2

            on = midi.NoteOnEvent(tick=tick_distance,
                                  velocity=MIDI_VELOCITY,
                                  pitch=midi_pitch)
            track.append(on)
            tick_distance = 0

        previous_time_step = cur_time_step
        tick_distance += midi_ticks_per_step

    for midi_pitch in range(MAX_MIDI_PITCH):
        note_type = previous_time_step[midi_pitch]
        if note_type != 0:
            off = midi.NoteOffEvent(tick=tick_distance, pitch=midi_pitch)
            track.append(off)
            tick_distance = 0

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    print('MIDI pattern completed.')
    return pattern
示例#6
0
def get_1111(pitch, pitch1, pitch2, patch3):
    on = midi.NoteOnEvent(tick=0, velocity=90, pitch=pitch)
    off = midi.NoteOffEvent(tick=100, pitch=pitch)
    track.extend([on, off])
    on = midi.NoteOnEvent(tick=0, velocity=85, pitch=pitch1)
    off = midi.NoteOffEvent(tick=100, pitch=pitch1)
    track.extend([on, off])
    on = midi.NoteOnEvent(tick=0, velocity=88, pitch=pitch2)
    off = midi.NoteOffEvent(tick=100, pitch=pitch2)
    track.extend([on, off])
    on = midi.NoteOnEvent(tick=0, velocity=83, pitch=patch3)
    off = midi.NoteOffEvent(tick=100, pitch=patch3)
    track.extend([on, off])
示例#7
0
def get_track2(track, pit, music_combine):
    pit = pit % 12
    posi = random.sample([0, 1], 1)[0]
    vel = 60
    print pit, posi
    new_pit = music_combine[pit][posi]
    track.append(midi.NoteOnEvent(tick=240, channel=1, velocity=vel, pitch=new_pit[0]))
    track.append(midi.NoteOnEvent(tick=0, channel=1, velocity=vel, pitch=new_pit[1]))
    track.append(midi.NoteOnEvent(tick=0, channel=1, velocity=vel, pitch=new_pit[2]))
    track.append(midi.NoteOffEvent(tick=240, channel=1, velocity=vel, pitch=new_pit[0]))
    track.append(midi.NoteOffEvent(tick=0, channel=1, velocity=vel, pitch=new_pit[1]))
    track.append(midi.NoteOffEvent(tick=0, channel=1, velocity=vel, pitch=new_pit[2]))
    return track
示例#8
0
def writeChord(tChord, track):
    if len(tChord.absChord) == 0:
        return
    absChd = tChord.absChord
    dur = tChord.dur
    tickDur = toMidiTick(dur)
    for a in absChd:
        track.append(
            midi.NoteOnEvent(tick=0, velocity=tChord.vol,
                             pitch=toMidiPitch(a)))
    track.append(midi.NoteOffEvent(tick=tickDur, pitch=toMidiPitch(absChd[0])))
    for a in absChd[1:]:
        track.append(midi.NoteOffEvent(
            tick=0, pitch=toMidiPitch(a)))  # Bug fix 26-July-2016
    def toMidi(self):
        print("called toMidi")
        print(self.noteName)
        # create midi pattern and track
        pattern = midi.Pattern()
        track = midi.Track()
        pattern.append(track)

        # append note events to the track
        print("start appending note events")
        tempo = midi.SetTempoEvent()
        tempo.set_bpm(self.bpm)
        track.append(tempo)

        rest = 0
        for i in range(len(self.noteName)):

            if self.noteName[i] == []:
                rest += 1

            for j in range(len(self.noteName[i])):
                on = midi.NoteOnEvent(tick=0 + (rest * self.resolution),
                                      velocity=self.constVelocity,
                                      pitch=self.noteName[i][j])
                track.append(on)
                rest = 0

            for k in range(len(self.noteName[i])):
                if k == 0:
                    off = midi.NoteOffEvent(tick=self.resolution,
                                            pitch=self.noteName[i][k])
                else:
                    off = midi.NoteOffEvent(tick=0, pitch=self.noteName[i][k])

                track.append(off)

        # create eot
        print("creating eot...")
        eot = midi.EndOfTrackEvent(tick=1)
        track.append(eot)

        print("This is the pattern")
        print(pattern)

        # save the pattern to ./output.mid
        print("Saving ...")
        midi.write_midifile(self.export + '.mid', pattern)

        print("Conversion finished")
示例#10
0
def makeSongMidi(song, instruments, volume, name, bpm):
    '''
    song is a list of lists of pysynth tuples
    instruments is a list of ints specifying midi instruments; -1 means to use
        channel 9 to produce percussion sounds
    volume is a list of ints specifying the volume of each track
    name is the song's name
    '''
    # 220 is completely arbitrary. anything >= 4 should probably work
    resolution = 220
    pattern = midi.Pattern(resolution=resolution)

    tempoEvent = midi.SetTempoEvent(tick=0)
    tempoEvent.set_bpm(bpm)
    tempoTrack = midi.Track()
    tempoTrack.append(tempoEvent)
    tempoTrack.append(midi.EndOfTrackEvent(tick=0))
    pattern.append(tempoTrack)

    for i in range(len(song)):
        track = midi.Track()
        if instruments[i] != -1:
            track.append(
                midi.ProgramChangeEvent(tick=0,
                                        channel=i,
                                        data=[instruments[i]]))
        for note in song[i]:
            noteLetter = note[0][:-1]
            noteNum = chromNotesNum[noteLetter] - 1
            octave = int(note[0][-1])
            pitch = noteNum + (octave - 1) * 12
            ticks = int(durationToBeats(note[1]) * resolution)
            if instruments[i] != -1:
                track.append(
                    midi.NoteOnEvent(tick=0,
                                     channel=i,
                                     data=[pitch, volume[i]]))
                track.append(
                    midi.NoteOffEvent(tick=ticks, channel=i, data=[pitch, 0]))
            else:
                track.append(
                    midi.NoteOnEvent(tick=0,
                                     channel=9,
                                     data=[pitch, volume[i]]))
                track.append(
                    midi.NoteOffEvent(tick=ticks, channel=9, data=[pitch, 0]))
        track.append(midi.EndOfTrackEvent(tick=0))
        pattern.append(track)
    midi.write_midifile('midi/' + name + '.mid', pattern)
示例#11
0
	def write_flam_note(self, note):
		on = midi.NoteOnEvent(tick = self.rest, velocity=120, pitch = note)
		self.track.append(on)
		off = midi.NoteOffEvent(tick = self.rest+self.note_tightness, pitch = note)
		self.track.append(off)

		on = midi.NoteOnEvent(tick = self.rest+1, velocity=120, pitch = note+2)
		self.track.append(on)
		off = midi.NoteOffEvent(tick = self.rest+2, pitch = note+2)
		self.track.append(off)

		self.rest = self.one_beat_value/self.beat_values_new["1/%d" % self.timing][1]
		self.rest *= self.rest_beats
		self.flam = False
		self.rest_beats = 1
示例#12
0
文件: edit.py 项目: akubishon/PiKey
 def addmidinote(self, note):
     if note.velocity:
         newnote = MIDI.NoteOnEvent(pitch=note.pitch, velocity=note.data[1])
     else:
         newnote = MIDI.NoteOffEvent(pitch=note.pitch)
     newnote.absoluteticks = note.absoluteticks
     self.piece.addmidinote(newnote, self.currenttrack)
示例#13
0
def add_note(long, velocity, pitch):
    global track
    # pitch: A4=57, A5=69
    on = midi.NoteOnEvent(tick=0, velocity=velocity, pitch=pitch)
    track.append(on)
    off = midi.NoteOffEvent(tick=long * 24, pitch=pitch)
    track.append(off)
示例#14
0
文件: util.py 项目: leb2/gan-music
    def piano_roll_to_midi(piano_roll, filename):
        """
        Saves a midi file from a piano_roll object

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

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

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

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

    tickoffset = 0
    for vector in grid:
        if previous_vector == vector: #if vectors are same, no new events
            tickoffset += 1
        else:
            for note_index in range(len(previous_vector)):
                if previous_vector[note_index] == vector[note_index]: #if same velocity, hold the note rather than rearticulate (no new event)
                    continue
                if previous_vector[note_index] != 0 and vector[note_index] == 0:
                    if note_index > 127:
                        print "BROKEN ASSUMPTION"
                    track.append(midi.NoteOffEvent(tick=tickoffset, pitch=note_index))
                else:
                    track.append(midi.NoteOnEvent(tick=0, velocity=vector[note_index], pitch=note_index))
                tickoffset = 0
            tickoffset += 1
        previous_vector = vector
    track.append(midi.EndOfTrackEvent(tick=1))
    return pattern
示例#16
0
def decoder(track, grid):
    previousVector = grid[0]
    # Search for first note in the grid
    for noteIndex, note in enumerate(previousVector):
        if note != 0:
            on = midi.NoteOnEvent(tick = 0, velocity = int(max(127,min(note,0))), pitch = noteIndex) #Add NoteOn event at tick = 0, velocity = previousVector[noteIndex], pitch = noteIndex
            track.append(on)
    # Turn off notes and add following        
    tickOffset = 0
    for vector in grid[1:]:
        if (previousVector == vector).all():
            tickOffset += 1
        else:
            for noteIndex, note in enumerate(previousVector):
                if note == vector[noteIndex]:
                    continue
                if note != 0 and vector[noteIndex] == 0:
                    off = midi.NoteOffEvent(tick = tickOffset, pitch = noteIndex)
                    track.append(off)
                else:
                    on = midi.NoteOnEvent(tick = 0, velocity =  int(max(127,min(vector[noteIndex],0))), pitch = noteIndex)
                    track.append(on)
                tickOffset = 0
            tickOffset += 1
        previousVector = vector

    return track
示例#17
0
	def write_note(self, note):
		print "NOTE:"
		print note
		if self.flam == True:
			self.write_flam_note(note)
		else:
			print "before - rest: %d rest_beats: %d" % (self.rest, self.rest_beats)
			self.rest *= self.rest_beats
			print "after - rest: %d rest_beats: %d" % (self.rest, self.rest_beats)
			
			velocity = 60

			if self.accent == True:
				velocity = 120

			self.accent = False

			# this is where the core of the timing stuff is going on it seems...
			on = midi.NoteOnEvent(tick = self.rest, velocity=velocity, pitch = note)
			print "midi on event generated at %d" % self.rest
			self.track.append(on)
			off = midi.NoteOffEvent(tick = self.note_tightness, pitch = note)
			self.track.append(off)
			self.rest = self.one_beat_value/self.beat_values_new["1/%d" % self.timing][1]
			print "self.rest"
			print self.rest
			self.rest_beats = 1
示例#18
0
 def event_read(self):
     ev = S.event_input(self.client)
     if ev and (ev < 0): self._error(ev)
     if ev and ev.type in (S.SND_SEQ_EVENT_NOTEON, S.SND_SEQ_EVENT_NOTEOFF,
                           S.SND_SEQ_EVENT_CONTROLLER):
         if ev.type == S.SND_SEQ_EVENT_NOTEON:
             mev = midi.NoteOnEvent()
             mev.channel = ev.data.note.channel
             mev.pitch = ev.data.note.note
             mev.velocity = ev.data.note.velocity
         elif ev.type == S.SND_SEQ_EVENT_NOTEOFF:
             mev = midi.NoteOffEvent()
             mev.channel = ev.data.note.channel
             mev.pitch = ev.data.note.note
             mev.velocity = ev.data.note.velocity
         elif ev.type == S.SND_SEQ_EVENT_CONTROLLER:
             mev = midi.ControlChangeEvent()
             mev.channel = ev.data.control.channel
             mev.control = ev.data.control.param
             mev.value = ev.data.control.value
         if ev.time.time.tv_nsec:
             # convert to ms
             mev.msdeay = \
                 (ev.time.time.tv_nsec / 1e6) + (ev.time.time.tv_sec * 1e3)
         else:
             mev.tick = ev.time.tick
         return mev
     else:
         return None
示例#19
0
def generate_random_midi():
    pattern = midi.Pattern(resolution=220)
    track = midi.Track()
    pattern.append(track)

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

        ticks += duration
        tick_buffer += duration

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

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

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

    return (pattern, pitches)
示例#20
0
def generate_audio_track(data, note_phrases, length, instrument=None):
    notes = data[0]["note_matrix"]
    if instrument is None:
        valid_instruments = list(
            set(notes.keys()).intersection(note_phrases.keys()))
        instrument = random.choice(valid_instruments)
    note_mats = [d["note_matrix"][instrument] for d in data]
    if len(note_phrases[instrument]) == 0:
        return None
    phrases = generate_note_sequence(note_phrases[instrument],
                                     note_mats,
                                     length,
                                     tick_max=160)

    track = midi.Track()
    track.append(midi.TrackNameEvent())
    prog = midi.ProgramChangeEvent()
    prog.set_value(instrument)
    track.append(prog)
    for i in xrange(0, len(phrases)):
        for j in xrange(0, len(phrases[i]["tick"])):
            pitch = phrases[i]["pitch"][j]
            velocity = phrases[i]["velocity"][j]
            note_type = phrases[i]["type"][j]
            tick = phrases[i]["tick"][j]
            obj = midi.NoteOnEvent(channel=0)
            if note_type == "off":
                obj = midi.NoteOffEvent(channel=0)
            obj.set_pitch(pitch)
            obj.set_velocity(velocity)
            obj.tick = tick
            track.append(obj)
    track.append(midi.EndOfTrackEvent())
    return track
示例#21
0
def generate_random_melody(end_tick, max_notes, min_init_pitch, max_init_pitch,
                           pitch_range, force_stop):
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    curr_tick = 0
    curr_note = 0
    curr_pitch = 0
    last_pitch = -1
    while curr_tick < end_tick and curr_note < max_notes:
        if last_pitch < 0:
            curr_pitch = random.randint(min_init_pitch, max_init_pitch)
        else:
            curr_pitch = last_pitch + random.randint(
                (pitch_range / 2) * -1, pitch_range / 2)
        on = midi.NoteOnEvent(tick=curr_tick, velocity=100, pitch=curr_pitch)
        track.append(on)
        last_for = end_tick / max_notes + random.randint(
            max_notes * -1, max_notes)
        curr_tick += last_for
        if curr_tick > end_tick and force_stop:
            curr_tick = end_tick
        off = midi.NoteOffEvent(tick=curr_tick, pitch=curr_pitch)
        track.append(off)
        last_pitch = curr_pitch
        curr_note += 1
    eot = midi.EndOfTrackEvent(tick=curr_tick)
    track.append(eot)
    return pattern
示例#22
0
    def generateChapter(self, pitch_list):
        headwait = 0
        startindex = 0
        strokes = []
        for i in range(self.chapterlength):
            if (pitch_list[i] == 0):
                headwait += self.interval
            else:
                startindex = i
                break

        tick = [self.interval] * self.chapterlength
        for i in range(startindex, self.chapterlength - 1):
            if (pitch_list[i] != 0):
                for j in range(i + 1, self.chapterlength):
                    if (pitch_list[j] == 0):
                        tick[i] += self.interval
                    else:
                        break
        for i in range(startindex, self.chapterlength):
            if (pitch_list[i] != 0):
                self.track.append(
                    midi.NoteOnEvent(tick=startindex * self.interval,
                                     velocity=self.velocity,
                                     pitch=pitch_list[i]))
                self.track.append(
                    midi.NoteOffEvent(tick=tick[i], pitch=pitch_list[i]))
                startindex = 0
示例#23
0
def test():
    """
    Make music!
    """
    initial = get_initial_state()
    node = get_successor_node(initial)
    for i in range(220):
        test_nodes = []
        for i in range(1000):
            test_nodes.append(get_successor_node(node))

        node = evaluate(node, test_nodes)

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

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

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

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

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

    # Add the end of track event, append it to the track
    eot = midi.EndOfTrackEvent(tick=0)
    track.append(eot)
    # Print out the pattern
    print pattern
    # Save the pattern to disk
    midi.write_midifile(fn, pattern)
示例#26
0
文件: edit.py 项目: akubishon/PiKey
    def extendcursorselection(self, aggressive=False):
        # quick delete
        tickmin, tickmax, midimin, midimax = self.selectcursorselection()
        # we hebben een selectie gaande...
        self.piece.deletenotes(self.selectednotes, self.currenttrack)
        extension = 0.5 * (aggressive + 1) * self.currentnoteticks
        i = 0
        while i < len(self.selectednotes):
            notei = self.selectednotes[i]
            j = i + 1
            while j < len(self.selectednotes):
                notej = self.selectednotes[j]
                if (notej[0] == notei[0]  # zelfde pitch
                        and notej[2] - config.EDITnotespace <=
                        notei[2] + notei[3] + extension):
                    # pitch is hetzelfde alleen zijn ze samengevoegd
                    # so extend notei up into notej
                    notei[3] = notej[3] + (notej[2] - notei[2]
                                           )  # nog niet verlengen
                    # note j "gedood" door i:
                    del self.selectednotes[j]
                else:
                    j += 1
            i += 1

        if self.selectednotes:
            for note in self.selectednotes:
                midinote = MIDI.NoteOnEvent(pitch=note[0], velocity=note[1])
                midinote.absoluteticks = note[2]
                self.addmidinote(midinote)
                if self.piece.deleteonnote(note[0], [
                        note[2],
                        note[2] + note[3] + extension + config.EDITnotespace
                ], self.currenttrack):
                    midinote = MIDI.NoteOffEvent(pitch=note[0])
                    midinote.absoluteticks = note[2] + note[3] + extension
                    self.addmidinote(midinote)

            if aggressive:
                alerttxt = "aggresief erg verlengde noten "
            else:
                alerttxt = "verlengde noten "

            self.setcurrentticksandload(self.currentabsoluteticks)
            if config.SMALLalerts:
                self.setalert(alerttxt[:-4])
            else:
                if midimax - midimin >= 127:
                    self.setalert(alerttxt + str(
                        int(
                            round(1.0 * (tickmax - tickmin) /
                                  self.currentnoteticks))) + " rows")
                else:
                    self.setalert(alerttxt + str(
                        int(
                            round(1.0 * (tickmax - tickmin) /
                                  self.currentnoteticks))) + " rows, " +
                                  str(midimax - midimin + 1) + " columns")
        else:
            self.setalert("geen noten om te verlengen.")
示例#27
0
def generateMidiNotes(pitches,track):
  for idx in range(len(pitches)):
    velocity = 0 if (pitches[idx] == pitches[idx-1]) else 100;
    on = midi.NoteOnEvent(tick=0, velocity=velocity, pitch=pitches[idx])
    track.append(on)
    off = midi.NoteOffEvent(tick=100, pitch=pitches[idx])
    track.append(off)
示例#28
0
def create_midi(text: str, sample_path: str, out_path: str):
    midifile = midi.read_midifile(sample_path)

    track = midifile[0][:]

    target = barcode_to_bin(create_barcode(text, "tmp"))
    target = [0] * 10 + target
    pos = 0
    for v in target:
        for i in range(80, 100):
            on = midi.NoteOnEvent(tick=0, velocity=1, pitch=i if v else 0)
            track.insert(pos, on)
            pos += 1
        track.insert(pos, midi.NoteOnEvent(tick=40, velocity=1, pitch=0))
        pos += 1
        for i in range(80, 100):
            off = midi.NoteOffEvent(tick=0, pitch=i if v else 0)
            track.insert(pos, off)
            pos += 1

    for i in range(pos, len(track) - 1):
        track.pop(pos)

    midifile.append(track)

    midi.write_midifile(out_path, midifile)
示例#29
0
def test_1():

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

        ), file=sys.stderr)

    file = "test.mid"

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

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

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

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

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

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

    midi.write_midifile(file, pattern)  #パターンをファイルに書き込みます。
示例#30
0
 def matrixToMidi(self, matrix, name="example"):
     pattern = midi.Pattern()
     track = midi.Track()
     pattern.append(track)
     tickCounter = 0
     for i in range(len(matrix)):
         for j in range(len(matrix[i])):
             if (matrix[i][j] == 0).any():
                 if not (matrix[i][j] == 0).all():
                     #print("Couple found: ")
                     #print(matrix[i][j])
                     #print("Response: a zero")
                     event = midi.NoteOffEvent(tick=tickCounter,
                                               pitch=j + self._lowerBound)
                     track.append(event)
                     tickCounter = 0
                 #else:
                 #print("Couple found: ")
                 #print(matrix[i][j])
                 #print("Response: [0, 0]")
             else:
                 #print("Couple found: ")
                 #print(matrix[i][j])
                 #print("Response: [1, 1]")
                 velocity = int(matrix[i][j][1])
                 event = midi.NoteOnEvent(tick=tickCounter,
                                          velocity=velocity,
                                          pitch=j + self._lowerBound)
                 track.append(event)
                 tickCounter = 0
         tickCounter = tickCounter + 1
     endOfTrack = midi.EndOfTrackEvent(tick=1)
     track.append(endOfTrack)
     #print(pattern)
     midi.write_midifile("generated/abc{}.mid".format(name), pattern)