def savefile(self):
        """Construct MIDI file and save"""
        global pad_records, instrument, pitch

        MyMIDI = MIDIFile(1)
        MyMIDI.addTempo(0, 0, 600)

        for i in range(0, total_pads):
            print len(pad_records["pad{0}".format(i+1)])
            MyMIDI.addProgramChange(0, i, 0, instrument[i])                            # set channel instrument
            print instrument[i]
            for j in range(0, len(pad_records["pad{0}".format(i+1)])):
                # print pad_records["pad{0}".format(i+1)][j]/8
                if j == 0:
                    MyMIDI.addNote(0, i, pitch[i], 0, len(pad_records["pad{0}".format(i+1)]), pad_records["pad{0}".format(i+1)][j]/8)
                    print "ch" + str(i) + " pitch: " + str(pitch[i]) + " vol:" + str(pad_records["pad{0}".format(i+1)][j]/8)
                else:
                    MyMIDI.addControllerEvent(0, i, j, 0x07, pad_records["pad{0}".format(i+1)][j]/8)
                    print " vol:" + str(pad_records["pad{0}".format(i+1)][j]/8)

        filename = self.browse_filepath.get() + "/" + self.saveFileName.get()
        # try:
        binfile = open(filename, 'wb')
        MyMIDI.writeFile(binfile)
        binfile.close()
        print "saved"
Beispiel #2
0
    def render(self, doc, output_file='output.mid'):
        ''' Produces actual output.
        Assumptions: separate channel for each DataObject'''
        # Note - I fixed a bug in MidiFile.py that was causing crashes (part of the midiutil lib).
        # Author confirms this is a bug, and will eventually fix and patch, but for now there's a
        # modified version of midiutil bundled with the project.

        # Create the MIDIFile Object with 1 track
        MyMIDI = MIDIFile(1)

        # Tracks are numbered from zero. Times are measured in beats.
        track = 0
        time = 0

        # Add track name and tempo.
        MyMIDI.addTrackName(track, time, "Sample Track")
        MyMIDI.addTempo(track, time, self.tempo)

        for channel, do in enumerate(doc):
            for cc_number, time_series in do.items():
                for i, val in enumerate(time_series):
                    time = float(i) / time_series.sample_rate
                    logging.debug(str(time) + ' ' + str(val))
                    MyMIDI.addControllerEvent(track, channel, time, cc_number,
                                              int(val))

        # And write it to disk.
        with open(output_file, 'wb') as binfile:
            MyMIDI.writeFile(binfile)
        return MyMIDI
Beispiel #3
0
    def render(self, doc, output_file='output.mid'):
        ''' Produces actual output.
        Assumptions: separate channel for each DataObject'''
        # Note - I fixed a bug in MidiFile.py that was causing crashes (part of the midiutil lib).
        # Author confirms this is a bug, and will eventually fix and patch, but for now there's a
        # modified version of midiutil bundled with the project.

        # Create the MIDIFile Object with 1 track
        MyMIDI = MIDIFile(1)

        # Tracks are numbered from zero. Times are measured in beats.
        track = 0
        time = 0

        # Add track name and tempo.
        MyMIDI.addTrackName(track, time, "Sample Track")
        MyMIDI.addTempo(track, time, self.tempo)

        for channel, do in enumerate(doc):
            for cc_number, time_series in do.items():
                for i, val in enumerate(time_series):
                    time = float(i) / time_series.sample_rate
                    logging.debug(str(time) + ' ' + str(val))
                    MyMIDI.addControllerEvent(track, channel, time, cc_number, int(val))

        # And write it to disk.
        with open(output_file, 'wb') as binfile:
            MyMIDI.writeFile(binfile)
        return MyMIDI
Beispiel #4
0
    def testAddControllerEvent(self):
        track = 0
        time = 0
        channel = 3
        controller_number = 1
        parameter = 2
        MyMIDI = MIDIFile(1)
        MyMIDI.addControllerEvent(track, channel, time, controller_number, parameter)
        MyMIDI.close()

        data = Decoder(MyMIDI.tracks[1].MIDIdata)

        self.assertEqual(MyMIDI.tracks[1].MIDIEventList[0].evtname, 'ControllerEvent')

        self.assertEqual(data.unpack_into_byte(0), 0x00)  # time
        self.assertEqual(data.unpack_into_byte(1), 0xB << 4 | channel)  # Code
        self.assertEqual(data.unpack_into_byte(2), controller_number)  # Controller Number
        self.assertEqual(data.unpack_into_byte(3), parameter)  # Controller Value
    def savefile(self):
        """Construct MIDI file and save"""
        global pad_records, instrument, pitch

        MyMIDI = MIDIFile(1)
        MyMIDI.addTempo(0, 0, 600)

        for i in range(0, total_pads):
            pad_active = False
            list_length = len(pad_records["pad{0}".format(i+1)])
            MyMIDI.addProgramChange(0, i, 0, instrument[i])                            # set channel instrument
            for j in range(0, list_length):
                velocity = pad_records["pad{0}".format(i+1)][j]/8
                if not pad_active and (velocity > 0):
                    MyMIDI.addNote(0, i, 60, 0, list_length-j, velocity)               # add note if velocity > 0 and pad not on
                    pad_active = True
                elif pad_active:
                    MyMIDI.addControllerEvent(0, i, j, 0x07, velocity)                 # change volume
                    if velocity == 0:
                        pad_active = False


        filename = self.browse_filepath.get() + "/" + self.saveFileName.get()
        try:
            binfile = open(filename, 'wb')
            MyMIDI.writeFile(binfile)
            binfile.close()
            # print "saved"
            tkMessageBox.showinfo(
                " ",
                "Saved MIDI file"
            )
        except:
            tkMessageBox.showerror(
                "Error",
                "Cannot save MIDI file"
            )
Beispiel #6
0
class Masterpiece(object):
    def __init__(self, rules_path="rules.json", length=4, tempo=90):
        self.rules_path = rules_path
        self.length = length
        self.tempo = tempo

        rules_file = open(rules_path, "r")
        rules = json.load(rules_file)
        rules_file.close()
        self.rhythm = rules["rhythm"]
        self.seq_chord = rules["seq_chord"]
        self.seq_perc = rules["seq_perc"]
        self.velocity = rules["velocity"]
        self.rn = RandomNote(rules["notes"], rules["interval_upper"],
                             rules["interval_lower"])

        self.MyMIDI = MIDIFile(3)
        self.current_track_number = 0

    def create_melody_sequence(self):
        seq_melody = []
        for i in range(self.length):
            for phrase in self.rhythm:
                self.rn.reset()
                for duration in phrase:
                    seq_melody.append((self.rn.random_note(), duration))
        return seq_melody

    def create_melody_track(self):
        seq_melody = self.create_melody_sequence()

        self.MyMIDI.addTrackName(track=self.current_track_number,
                                 time=0,
                                 trackName="piano")
        self.MyMIDI.addTempo(track=self.current_track_number,
                             time=0,
                             tempo=self.tempo)
        self.MyMIDI.addProgramChange(tracknum=self.current_track_number,
                                     channel=0,
                                     time=0,
                                     program=0)

        pos = 0
        for pitch, duration in seq_melody:
            relative_pos = pos - int(pos / 4) * 4
            if 0 <= relative_pos < 1:
                vol = self.velocity["strong"]
            elif 2 <= relative_pos < 3:
                vol = self.velocity["intermediate"]
            else:
                vol = self.velocity["weak"]
            self.MyMIDI.addNote(track=self.current_track_number,
                                channel=0,
                                pitch=pitch,
                                time=pos,
                                duration=duration,
                                volume=vol)
            if relative_pos in [0, 2]:
                self.MyMIDI.addControllerEvent(track=self.current_track_number,
                                               channel=0,
                                               time=pos,
                                               controller_number=64,
                                               parameter=127)
                self.MyMIDI.addControllerEvent(track=self.current_track_number,
                                               channel=0,
                                               time=pos + 1.96875,
                                               controller_number=64,
                                               parameter=0)
            pos += duration
        self.current_track_number += 1

    def create_chord_track(self):
        self.MyMIDI.addTrackName(track=self.current_track_number,
                                 time=0,
                                 trackName="chords")
        self.MyMIDI.addTempo(track=self.current_track_number,
                             time=0,
                             tempo=self.tempo)
        self.MyMIDI.addProgramChange(tracknum=self.current_track_number,
                                     channel=0,
                                     time=0,
                                     program=0)

        # C  D  E  F  G  A  B  | C  D  E  F  G  A  B  | C
        # 48 50 52 53 55 57 59 | 60 62 64 65 67 69 71 | 72

        pos = 0
        while pos < self.length * 16:
            for item in self.seq_chord:
                for pitch in item:
                    self.MyMIDI.addControllerEvent(
                        track=self.current_track_number,
                        channel=0,
                        time=pos,
                        controller_number=64,
                        parameter=127)
                    self.MyMIDI.addControllerEvent(
                        track=self.current_track_number,
                        channel=0,
                        time=pos + 1.96875,
                        controller_number=64,
                        parameter=0)
                    self.MyMIDI.addNote(track=self.current_track_number,
                                        channel=0,
                                        pitch=pitch,
                                        time=pos,
                                        duration=2,
                                        volume=76)
                    self.MyMIDI.addControllerEvent(
                        track=self.current_track_number,
                        channel=0,
                        time=pos + 2,
                        controller_number=64,
                        parameter=127)
                    self.MyMIDI.addControllerEvent(
                        track=self.current_track_number,
                        channel=0,
                        time=pos + 3.96875,
                        controller_number=64,
                        parameter=0)
                    self.MyMIDI.addNote(track=self.current_track_number,
                                        channel=0,
                                        pitch=pitch,
                                        time=pos + 2,
                                        duration=2,
                                        volume=68)
                pos += 4
        self.current_track_number += 1

    def create_perc_track(self):
        self.MyMIDI.addTrackName(track=self.current_track_number,
                                 time=0,
                                 trackName="perc")
        self.MyMIDI.addTempo(track=self.current_track_number,
                             time=0,
                             tempo=self.tempo)
        self.MyMIDI.addProgramChange(tracknum=self.current_track_number,
                                     channel=9,
                                     time=0,
                                     program=0)

        pos = 0
        while pos < self.length * 16:
            if pos != 0:
                self.MyMIDI.addNote(track=self.current_track_number,
                                    channel=9,
                                    pitch=49,
                                    time=pos,
                                    duration=0.5,
                                    volume=102)
            for pitch, duration in self.seq_perc:
                relative_pos = pos - int(pos / 4) * 4
                if 0 <= relative_pos < 1:
                    vol = 102
                elif 2 <= relative_pos < 3:
                    vol = 96
                else:
                    vol = 92
                self.MyMIDI.addNote(track=self.current_track_number,
                                    channel=9,
                                    pitch=pitch,
                                    time=pos,
                                    duration=duration,
                                    volume=vol)
                pos += duration
        self.current_track_number += 1

    def create_midi_file(self, filename, melody=True, chord=True, perc=True):
        if melody:
            self.create_melody_track()
        if chord:
            self.create_chord_track()
        if perc:
            self.create_perc_track()
        with open(filename, "wb") as midi_file:
            self.MyMIDI.writeFile(midi_file)
def reconstruction(path):
    fp = path

    selectedTrackNum = 1

    #printTracks = True
    printTracks = False

    programChangeOn = False
    deltaTimeOn = False

    ### Music21 Initalizations
    mf = midi.MidiFile()
    mf.open(fp)
    mf.read()
    mf.close()
    ###

    ### MIDIUtil Initalizations
    MyMIDI = MIDIFile(len(mf.tracks))
    volume = 100
    tempo = 680
    duration = 6  # interval time that key is still pressed
    ###

    MyMIDI.addTempo(0, 0, tempo)

    prevPitch = -1

    mtf = midi.MidiFile()

    mt = midi.MidiTrack(len(mf.tracks))
    #mtf.tracks = mt

    # Gets the number of events in our chosen track
    numOfEvents = len(mf.tracks[selectedTrackNum].events)
    tracksNum = selectedTrackNum

    count = 0

    # Begin reconstruction of the track
    for eventInd in range(0, numOfEvents):

        event = mf.tracks[tracksNum].events[eventInd]
        eventType = event.type

        me = midi.MidiEvent(mt)
        me.type = eventType

        # event
        event = mf.tracks[tracksNum].events[eventInd]
        eventType = event.type

        if printTracks:
            print event

        pitch = event.pitch
        velocity = event.velocity
        channel = event.channel
        time = event.time
        volume = event.velocity

        if deltaTimeOn:
            # determine the duration using DeltaTime
            # First checking if we are at last note o track
            if numOfEvents > eventInd + 1:

                # Now we get DeltaTime from the next MidiEvent and use that as duration
                nextStepType = mf.tracks[tracksNum].events[eventInd + 1]
                if nextStepType.type == 'DeltaTime':
                    duration = nextStepType.time / 100

        if time is not None:
            time = event.time
        else:
            time = count

        if eventType == 'NOTE_ON':

            MyMIDI.addNote(0, channel, pitch, time, duration, volume)

        # Controls instruments
        if programChangeOn:
            if eventType == 'PROGRAM_CHANGE':
                MyMIDI.addProgramChange(0, channel, time, event.data)

        if eventType == 'CONTROLLER_CHANGE':
            MyMIDI.addControllerEvent(0, channel, time, event._parameter2,
                                      event._parameter1)

        prevPitch = event.pitch

        count = count + 1

    # Writing reconstructed track
    print 'Went through Track ', selectedTrackNum

    binfile = open("result.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
Beispiel #8
0
                

                if eventType == 'NOTE_ON':
                    duration = 6
                    MyMIDI.addNote(track=tracksNum, channel=channel, pitch=pitch, time=time, duration=duration, volume=volume)
                    saveStr = 'track: ' + str(tracksNum) + '  channel: ' + str(channel) + '  pitch: ' + str(pitch) + '  duration: ' + str(duration)  + '  time: ' + str(time) + '\n'
                    f.write(saveStr)


                # Controls instruments  
                if programChangeOn:             
                        if eventType == 'PROGRAM_CHANGE':
                            MyMIDI.addProgramChange(track=tracksNum, channel=channel, time=time, program=event.data)
                
                if controllerChangeOn:  
                        if eventType == 'CONTROLLER_CHANGE':
                            MyMIDI.addControllerEvent(track=tracksNum, channel=channel, time=time, controller_number=event.parameter2, parameter=event.parameter1)
                

                #prevPitch = event.pitch

                count = count + 1
        f.close()

# Writing reconstructed track
print('Went through ', len(mf.tracks), ' tracks')

binfile = open("resultTwolib.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()    
Beispiel #9
0
def YoutubeToMIDIConvert(url):

	# First we convert Youtube video to mp3

	print 'Working with ', url
	YT_URL = url

	print os.getcwd()

	'''
	print 'Paste the URL of the Youtube video and press [Enter]'
	YT_URL = raw_input()
	'''

	ydl_opts = {
	    'outtmpl': 'bin/output.mp3',
	    'format': 'bestaudio/best',
	    'postprocessors': [{
		'key': 'FFmpegExtractAudio',
		'preferredcodec': 'mp3',
		'preferredquality': '192',
	    }],
	}
	with youtube_dl.YoutubeDL(ydl_opts) as ydl:
	    ydl.download([YT_URL])


	# Then we convert mp3 video to midi
	os.system('python2 ' + os.path.dirname(os.path.realpath(__file__)) + '/support/audio_to_midi_melodia.py bin/output.mp3 bin/output.mid 60 --smooth 0.25 --minduration 0.1 --jams')

	# Insert code here to remove delta time

	selectedTrackNum = 0

	fp = 'bin/output.mid'
	printTracks = False

	programChangeOn = False
	deltaTimeOn = False


	### Music21 Initalizations
	mf = midi.MidiFile()
	mf.open(fp)
	mf.read()
	mf.close()
	###

	### MIDIUtil Initalizations
	MyMIDI = MIDIFile(len(mf.tracks))
	volume = 100
	tempo = 680
	duration = 6   # interval time that key is still pressed
	###

	MyMIDI.addTempo(0,0,tempo)

	prevPitch = -1

	mtf = midi.MidiFile()



	mt = midi.MidiTrack(len(mf.tracks))
	#mtf.tracks = mt


	# Gets the number of events in our chosen track
	numOfEvents = len(mf.tracks[selectedTrackNum].events)
	tracksNum = selectedTrackNum

	count = 0

	# Begin reconstruction of the track
	for eventInd in range(0,numOfEvents):

		event = mf.tracks[tracksNum].events[eventInd]
		eventType = event.type

		me = midi.MidiEvent(mt)		
		me.type = eventType


		# event
		event = mf.tracks[tracksNum].events[eventInd]
		eventType = event.type

		if printTracks:
			print event

		pitch = event.pitch
		velocity = event.velocity
		channel = event.channel
		time = event.time
		volume = event.velocity


		if deltaTimeOn:
			# determine the duration using DeltaTime
			# First checking if we are at last note o track
			if numOfEvents > eventInd + 1:

			    # Now we get DeltaTime from the next MidiEvent and use that as duration
			    nextStepType = mf.tracks[tracksNum].events[eventInd + 1]
			    if nextStepType.type == 'DeltaTime':
				duration = nextStepType.time/100		



		if time is not None:
		    time = event.time
		else:
		    time = count



		if eventType == 'NOTE_ON':


		    MyMIDI.addNote(0, channel, pitch, time, duration, volume)

		# Controls instruments	
		if programChangeOn:		
			if eventType == 'PROGRAM_CHANGE':
			    MyMIDI.addProgramChange(0, channel, time, event.data)
		
			
		if eventType == 'CONTROLLER_CHANGE':
		    MyMIDI.addControllerEvent(0, channel, time, event._parameter2, event._parameter1)
		

		prevPitch = event.pitch

		count = count + 1


	# Writing reconstructed track
	print 'Went through Track ', selectedTrackNum

	binfile = open(fp, 'wb')
	MyMIDI.writeFile(binfile)
	binfile.close()  


	#########
	os.system('cp bin/output.mid convertYTtoMidi/bin/output.mid')

	

	####
	print 'File successfully converted!'
Beispiel #10
0
class Music():
    def __init__(self, rules_path="rules.json", length=4, tempo=90):
        rulesPath = open(rules_path, "r")
        rules = json.load(rulesPath)
        rulesPath.close()

        self.length = length
        self.tempo = tempo

        self.rhythms = []
        self.rhythms.append(rules["rhythms"]["Little Star_01"])  # 读取小星星节奏规则 16拍4小节
        self.rhythms.append(rules["rhythms"]["Little Star_02"])  # 读取小星星节奏规则 16拍4小节


        self.seq_chord = rules["seq_chord"]  # 读取和弦规则
        self.seq_perc = rules["seq_perc"]  # 读取击打乐规则
        self.velocity = rules["velocity"]  # 读取速率

        self.notes = rules["notes"]["01"]
        self.interval_upper = rules["interval_upper"]
        self.interval_lower = rules["interval_lower"]

        self.MyMIDI = MIDIFile(3)   # 创建三轨道
        self.perc_trackNumber = 0
        self.chord_trackNumber = 1


    # 限制音域随机音调
    def random01_note(self):
        last_played = 0
        while True:
            note = random.choice(range(1, len(self.notes) + 1))
            if not last_played:
                break
            else:
                # 音程限制
                if random.choice(self.interval_upper) >= abs(note - last_played) >= random.choice(self.interval_lower):
                    break
                else:
                    continue
        last_played = note
        return self.notes[last_played - 1]

    # 不限制音域随机音调
    def random02_note(self):
        note = random.choice(range(1, len(self.notes) + 1))
        last_played = note
        return self.notes[last_played - 1]

    # 创建打击乐
    def create_perc_track(self):
        self.MyMIDI.addTrackName(
            track=self.perc_trackNumber,
            time=0, trackName="perc")
        self.MyMIDI.addTempo(
            track=self.perc_trackNumber,
            time=0, tempo=self.tempo)
        self.MyMIDI.addProgramChange(
            tracknum=self.perc_trackNumber,
            channel=9, time=0, program=0)

        pos = 0
        while pos < self.length * 16:
            if pos != 0:
                self.MyMIDI.addNote(
                    track=self.perc_trackNumber,
                    channel=9, pitch=49, time=pos, duration=0.5, volume=102)
            for pitch, duration in self.seq_perc:
                relative_pos = pos - int(pos / 4) * 4
                if 0 <= relative_pos < 1:
                    vol = 102
                elif 2 <= relative_pos < 3:
                    vol = 96
                else:
                    vol = 92
                self.MyMIDI.addNote(
                    track=self.perc_trackNumber,
                    channel=9, pitch=pitch, time=pos, duration=duration, volume=vol)
                pos += duration

    # 创建钢琴乐
    def create_piano_track(self, number):
        seq_melody = []  # 创建序列
        for i in range(self.length):  # 读取长度
            for phrase in self.rhythms[number]:  # 读取节奏
                for duration in phrase:
                    seq_melody.append((self.random01_note(), duration))  # 随机音调

        self.MyMIDI.addTrackName(
            track=number,
            time=0, trackName="piano")
        self.MyMIDI.addTempo(
            track=number,
            time=0, tempo=self.tempo)
        self.MyMIDI.addProgramChange(
            tracknum=number,
            channel=0, time=0, program=0)

        pos = 0
        for pitch, duration in seq_melody:
            relative_pos = pos - int(pos / 4) * 4
            if 0 <= relative_pos < 1:
                vol = self.velocity["strong"]
            elif 2 <= relative_pos < 3:
                vol = self.velocity["intermediate"]
            else:
                vol = self.velocity["weak"]
            self.MyMIDI.addNote(
                track=number,
                channel=0, pitch=pitch, time=pos, duration=duration, volume=vol)
            if relative_pos in [0, 2]:
                self.MyMIDI.addControllerEvent(
                    track=number,
                    channel=0, time=pos, controller_number=64, parameter=127)
                self.MyMIDI.addControllerEvent(
                    track=number,
                    channel=0, time=pos + 1.96875, controller_number=64, parameter=0)
            pos += duration

    # 创建和弦
    def create_chord_track(self):
        self.MyMIDI.addTrackName(
            track=self.chord_trackNumber,
            time=0, trackName="chords")
        self.MyMIDI.addTempo(
            track=self.chord_trackNumber,
            time=0, tempo=self.tempo)
        self.MyMIDI.addProgramChange(
            tracknum=self.chord_trackNumber,
            channel=0, time=0, program=0)

        # C  D  E  F  G  A  B  | C  D  E  F  G  A  B  | C
        # 48 50 52 53 55 57 59 | 60 62 64 65 67 69 71 | 72

        pos = 0
        while pos < self.length * 16:
            for item in self.seq_chord:
                for pitch in item:
                    self.MyMIDI.addControllerEvent(
                        track=self.chord_trackNumber,
                        channel=0, time=pos, controller_number=64, parameter=127)
                    self.MyMIDI.addControllerEvent(
                        track=self.chord_trackNumber,
                        channel=0, time=pos + 1.96875, controller_number=64, parameter=0)

                    self.MyMIDI.addNote(
                        track=self.chord_trackNumber,
                        channel=0, pitch=pitch, time=pos, duration=2, volume=76)

                    self.MyMIDI.addControllerEvent(
                        track=self.chord_trackNumber,
                        channel=0, time=pos + 2, controller_number=64, parameter=127)
                    self.MyMIDI.addControllerEvent(
                        track=self.chord_trackNumber,
                        channel=0, time=pos + 3.96875, controller_number=64, parameter=0)

                    self.MyMIDI.addNote(
                        track=self.chord_trackNumber,
                        channel=0, pitch=pitch, time=pos + 2, duration=2, volume=68)
                pos += 4

    # 创建文件(单一版本)
    def create_file(self, filename, piano=True, chord=True, perc=True):
        if piano:
            self.create_piano_track(0)
            self.create_piano_track(1)
        if chord:
            self.create_chord_track()
        if perc:
            self.create_perc_track()
        with open(filename, "wb") as midi_file:
            self.MyMIDI.writeFile(midi_file)
Beispiel #11
0
class Masterpiece(object):
    c_major_scale = [
        33, 35, 36, 38, 40, 41, 43, 45, 47, 48, 50, 52, 53, 55, 57, 59, 60, 62,
        64, 65, 67, 69, 71, 72, 74, 76, 77, 79, 81, 83, 84
    ]
    offsets = {'a': -3, 'b': -1, 'c': 0, 'd': 2, 'e': 4, 'f': 5, 'g': 7}

    def __init__(self, rules, rhythm, args):
        self.length = args.num_exercises
        self.tempo = args.tempo
        self.rhythm = rhythm

        self.key = args.key
        self.offset = Masterpiece.offsets[self.key[0]]
        if len(self.key) == 3:
            if self.key[1:] == 'es':
                self.offset -= 1
            else:
                self.offset += 1

        self.notes = [
            note + self.offset for note in Masterpiece.c_major_scale
            if note + self.offset >= 48 and note + self.offset <= 72
        ]

        self.rules = rules
        self.rn = RandomNote(self.notes, rules['interval_upper'],
                             rules['interval_lower'])

        self.MyMIDI = MIDIFile(3)

    def create_melody_sequence(self):
        seq_melody = []
        lilypond_str = '\\version "2.18.2"\n\n'
        lilypond_str += '\\header {\n    title = "'
        lilypond_str += f'Note Reading Exercises in {self.key[0].upper()}'
        if len(self.key) == 3:
            if self.key[1:] == 'is':
                lilypond_str += '♯'
            else:
                lilypond_str += '♭'
        lilypond_str += ' Major'
        lilypond_str += '"\n}\n\n'

        for i in range(self.length):
            for phrase in self.rhythm:
                lilypond_str += '{\n    \\time 4/4\n    '
                lilypond_str += '\\key c \\major\n    '
                lilypond_str += '\\transpose c '
                lilypond_str += self.key
                if self.key[0] in 'ab':
                    lilypond_str += ','
                lilypond_str += ' {\n        '
                self.rn.reset()
                for duration in phrase:
                    note = self.rn.random_note()
                    seq_melody.append((note, duration))
                    note_index = Masterpiece.c_major_scale.index(note -
                                                                 self.offset)
                    offset = note_index % 7
                    note_name = chr(ord('a') + offset % 7)
                    note_name += "'" * ((note_index - 2) // 7)
                    lilypond_str += f'{note_name} '
                lilypond_str += '\n    }\n}\n'

        return seq_melody, lilypond_str

    def create_melody_track(self):
        seq_melody, lilypond_str = self.create_melody_sequence()

        self.MyMIDI.addTrackName(track=0, time=0, trackName='piano')
        self.MyMIDI.addTempo(track=0, time=0, tempo=self.tempo)
        self.MyMIDI.addProgramChange(tracknum=0, channel=0, time=0, program=0)

        pos = 4
        for pitch, duration in seq_melody:
            relative_pos = pos - int(pos / 4) * 4
            if 0 <= relative_pos < 1:
                vol = self.rules['velocity']['strong']
            elif 2 <= relative_pos < 3:
                vol = self.rules['velocity']['intermediate']
            else:
                vol = self.rules['velocity']['weak']
            self.MyMIDI.addNote(track=0,
                                channel=0,
                                pitch=pitch,
                                time=pos,
                                duration=duration,
                                volume=vol)
            if relative_pos in [0, 2]:
                self.MyMIDI.addControllerEvent(track=0,
                                               channel=0,
                                               time=pos,
                                               controller_number=64,
                                               parameter=127)
                self.MyMIDI.addControllerEvent(track=0,
                                               channel=0,
                                               time=pos + 1.96875,
                                               controller_number=64,
                                               parameter=0)
            pos += duration

        return lilypond_str

    def create_midi_file(self, filename):
        lilypond_str = self.create_melody_track()
        with open(filename, 'wb') as midi_file:
            self.MyMIDI.writeFile(midi_file)

        return lilypond_str
Beispiel #12
0
            time = count



        if eventType == 'NOTE_ON':


            MyMIDI.addNote(0, channel, pitch, time, duration, volume)

        # Controls instruments  
        if programChangeOn:             
                if eventType == 'PROGRAM_CHANGE':
                    MyMIDI.addProgramChange(0, channel, time, event.data)
        
                
        if eventType == 'CONTROLLER_CHANGE':
            MyMIDI.addControllerEvent(0, channel, time, event.parameter2, event.parameter1)
        

        prevPitch = event.pitch

        count = count + 1


# Writing reconstructed track
print('Went through Track ', selectedTrackNum)

binfile = open("result.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()    
Beispiel #13
0
from midiutil.MidiFile import MIDIFile

# Create the MIDIFile Object with 1 track
MyMIDI = MIDIFile(1)

# Tracks are numbered from zero. Times are measured in beats.
track = 0
time = 0

# Add track name and tempo.
MyMIDI.addTrackName(track, time, "Sample Track")
MyMIDI.addTempo(track, time, 120)

# Add a note. addNote expects the following information:
track = 0
channel = 0
pitch = 60
time = 0
duration = 1
volume = 100

# Now add the note.
for time in range(10):
    # MyMIDI.addNote(track,channel,pitch,time,duration,volume)
    MyMIDI.addControllerEvent(track, channel, time, 0x10, 10 * time)  # cc 74

# And write it to disk.
binfile = open("output.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()
Beispiel #14
0
# Tracks are numbered from zero. Times are measured in beats.
track = 0
time = 0


# Add track name and tempo.
MyMIDI.addTrackName(track, time, "Sample Track")
MyMIDI.addTempo(track, time, 120)


# Add a note. addNote expects the following information:
track = 0
channel = 0
pitch = 60
time = 0
duration = 1
volume = 100


# Now add the note.
for time in range(10):
    # MyMIDI.addNote(track,channel,pitch,time,duration,volume)
    MyMIDI.addControllerEvent(track, channel, time, 0x10, 10 * time) # cc 74


# And write it to disk.
binfile = open("output.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()