Ejemplo n.º 1
1
def init(parent):
    global sp_midi, chord_count, bass_count, melody_count, drums_count

    chord_count = 0
    bass_count = 0
    melody_count = 0
    drums_count = 0

    sp_midi = MIDIFile(5)
    time = 0

    sp_midi.addTrackName(mixer.channels["drums"], time, "Drums")
    sp_midi.addProgramChange(mixer.channels["drums"], 10, 0, 118)

    sp_midi.addTrackName(mixer.channels["bass"], time, "Bass")
    sp_midi.addProgramChange(mixer.channels["bass"], mixer.channels["bass"], 0,
                             34)

    sp_midi.addTrackName(mixer.channels["chords"], time, "Chords")
    sp_midi.addProgramChange(mixer.channels["chords"],
                             mixer.channels["chords"], 0, 88)

    sp_midi.addTrackName(mixer.channels["melody"], time, "Melody")
    sp_midi.addProgramChange(mixer.channels["melody"],
                             mixer.channels["melody"], 0, 26)
    print performer.bpm
    sp_midi.addTempo(0, 0, parent.user_tempo)
Ejemplo n.º 2
0
    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"
Ejemplo n.º 3
0
    class FileOutput(Output):
        url_example = "file://foo.mid"

        def __init__(self, url):
            Output.__init__(self)
            outfile = url.netloc + url.path

            if not outfile:
                print "file:// output needs a filename"
                raise ValueError("File output needs a filename")

            log.info("Opening File output: %s", outfile)
            self.midi = MIDIFile(1)
            self.midi.addTrackName(0, 0, "Mic2Mid Track 0")
            self.midi.addTempo(0, 0, 60)
            self.midi.addProgramChange(0, 0, 0, 27)
            self.start = time.time()
            self.filename = outfile

        def close(self):
            Output.close(self)
            log.info("Closing File output: %s", self.filename)
            fp = open(self.filename, "wb")
            self.midi.writeFile(fp)
            fp.close()

        def note_on(self, note):
            self.midi.addNote(0, 0, self.note_to_midi(note), time.time() - self.start, 1, 100)
Ejemplo n.º 4
0
def create_midi_file(ensemble, tempo):

    num_players = len(ensemble.G)
    mf = MIDIFile(num_players)
    channel = 0  #all on the same channel?

    for node in ensemble.G.nodes():

        # initialize new track
        track = node  #track index is the same as node index
        time = 0  #start at beginning
        mf.addTrackName(track, time, "Player {}".format(node))
        mf.addProgramChange(track, channel, time, 42)
        mf.addTempo(track, time, tempo)

        #get player object and get data
        player = ensemble.G.nodes[node]['player']
        data = player.data

        #add notes from (# note time = 0 here)
        for pitch, volume, duration in data:
            mf.addNote(track, channel, pitch, time, duration, volume)
            time += duration

    return savefile(mf)
Ejemplo n.º 5
0
def generate(n,
             program,
             suffix,
             sf="/usr/share/sounds/sf2/FluidR3_GM.sf2",
             volume=100):
    MyMIDI = MIDIFile(2)
    track = 0
    time = 0
    MyMIDI.addTrackName(track, time, "Test")
    MyMIDI.addTempo(track, time, 30)
    track = 0
    channel = 0
    time = 0
    duration = 2.0
    MyMIDI.addProgramChange(track, channel, 0, program)
    MyMIDI.addNote(track, channel, plist[n], 0, duration, volume)
    binfile = open("output.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()

    os.system("fluidsynth %s output.mid -F output.wav --sample-rate 1000" % sf)
    os.system("lame -V 7 output.wav sound%d%s.mp3" % (n, suffix))
    #	os.system("avconv -i output.wav  -acodec sound%d%s.aac" % (n, suffix))
    os.system("rm output.mid")
    #	os.system("mplayer output.wav")
    os.system("mv output.wav sound%d%s.wav" % (n, suffix))
Ejemplo n.º 6
0
def __play(arg_time, tone: str, octave: str):
    # CREATE MEMORY FILE
    memFile = BytesIO()
    MyMIDI = MIDIFile(1, adjust_origin=True)
    track = 0
    time = 0
    channel = 0
    pitch = int(__get_tones(tone, octave))
    duration = arg_time
    volume = 100
    MyMIDI.addProgramChange(track, channel, time, 90)
    MyMIDI.addTempo(track, time, 60)

    # WRITE A SCALE
    MyMIDI.addNote(track, channel, pitch, time, duration + 1, volume)
    MyMIDI.writeFile(memFile)

    # PLAYBACK

    clock = Clock()
    # memFile.seek(0)  # THIS IS CRITICAL, OTHERWISE YOU GET THAT ERROR!
    temp = BytesIO(memFile.getvalue())
    pygame.mixer.music.load(temp)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        clock.tick(1)
Ejemplo n.º 7
0
def midiwrite(outfile, notes, tempo):

    track = 0
    time = 0
    midifile = MIDIFile(1) # Just one track for now
    channel = 0
    volume = 100
    program = 1 # Bright piano
    
    # Add track name and tempo.
    midifile.addTrackName(track, time, "Synth Track")
    midifile.addTempo(track, time, tempo)
    midifile.addProgramChange(track, channel, time, program)

    for note in notes:
        onset = note[0] * (tempo/60.)
        duration = note[1] * (tempo/60.)
        # duration = 1
        pitch = note[2]
        midifile.addNote(track, channel, pitch, onset, duration, volume)

    # And write it to disk.
    binfile = open(outfile, 'wb')
    midifile.writeFile(binfile)
    binfile.close()
Ejemplo n.º 8
0
    def generate_midi(self):
        MyMIDI = MIDIFile(1)
        s = len(self.prob_matrix)

        track = 0
        time = 0
        volume = 110
        channel = 0
        program = self.get_instrument(self.instrument)
        pitch = numpy.random.randint(0, s, 1)[0]

        MyMIDI.addTempo(track, time, self.bpm)
        MyMIDI.addProgramChange(track, channel, time, program)

        for i in range (0,int(self.length*self.bpm)):
            pitch = (numpy.random.choice(s, 1, False, self.prob_matrix[pitch % s])[0])
            if self.rand:
                pitch += (12 * numpy.random.randint(0, 2, 1)[0]) + numpy.random.randint(2*s, 5*s, 1)[0]
                pitch = pitch % 128

            duration = numpy.random.randint(50, 400, 1)[0] / 200
            MyMIDI.addNote(track, channel, pitch, time, duration, volume)
            time += duration

        os.makedirs(os.path.dirname(self.path), exist_ok=True)
        with open(self.path, "wb") as f:
            MyMIDI.writeFile(f)
            f.close()
Ejemplo n.º 9
0
class Midi:
    """Musique midi"""
    def __init__(self, partition, titre, tempo):
        # Définition des paramètres MIDI.
        piste = 0
        temps = 0
        self.tempo = tempo / 2
        self.sortiemidi = MIDIFile(1, file_format=1)
        # Nom de la piste.
        self.sortiemidi.addTrackName(piste, temps, sansaccents(titre))
        # Tempo.
        self.sortiemidi.addTempo(piste, temps, self.tempo)
        # Instrument (74 : flûte).
        self.sortiemidi.addProgramChange(piste, 0, temps, 74)
        self.traiter_partition(partition, piste, temps)

    def traiter_partition(self, partition, piste, temps):
        """Création des évènements MIDI"""
        transposition = partition.transposition
        channel = 0
        volume = 127
        for mot in partition:
            for i, syllabe in enumerate(mot):
                syl = str(syllabe)
                if i + 1 < len(mot):
                    syl = syl + '-'
                for j, note in enumerate(
                        notes for notes in syllabe.musique
                        if isinstance(notes, Note)
                ):
                    pitch = note.hauteur + transposition
                    duree = int(note.duree)
                    self.sortiemidi.addTempo(
                        piste, temps, (self.tempo * duree / note.duree)
                    )
                    self.sortiemidi.addNote(
                        piste,
                        channel,
                        pitch,
                        temps,
                        duree / 2,
                        volume
                    )
                    if j == 0:
                        self.sortiemidi.addText(
                            piste,
                            temps,
                            syl
                        )
                    temps += duree / 2

    def ecrire(self, chemin):
        """Écriture effective du fichier MIDI"""
        with (
            open(sys.stdout.fileno(), 'wb')
            if chemin == '-'
            else open(chemin, 'wb')
        ) as sortie:
            self.sortiemidi.writeFile(sortie)
Ejemplo n.º 10
0
class midiFile:
	"""
		Allows MIDI files to be gradually built up.

		On creation, a MIDI file track is created, and notes are added through calls
		to addNote.

		The file can be saved through a call to writeFile.

		More information on the library being used at:
			http://www.emergentmusics.org/mididutil-class-reference
	"""

	def __init__(self, trackName, maxPackageDepth, bpm):
		self.state = MIDIFile(1) #Number of tracks.
		
		self.time = 0
		self.track = 0
		self.state.addTempo(self.track,self.time,bpm)
		self.maxPackageDepth = maxPackageDepth
		self.minPitch = 0	
		self.maxPitch = 127

	def setPitchRange(self, min, max):
		""" Set the range (somewhere between 0-127) that will be used in assigning pitch to notes,
			which is based on package depth.
		"""
		self.minPitch = min
		self.maxPitch = max

	def addNote(self, depth, instrument, duration):
		"""	Adds a new note to the MIDI file.
			Increments the time by 1 on addition of every note.

			depth: Package structure depth. Used to determine the pitch of the note.
			instrument: Number from 0-127 (see: http://en.wikipedia.org/wiki/General_MIDI#Program_change_events)
			duration: Number of beats note should be played over.
		"""

		channel = 0
		pitch = getPitch(depth, self.maxPackageDepth, self.minPitch, self.maxPitch)

		volume = 127

		logging.info("Adding note, with instrument {0}, pitch {1}, duration {2}".format(instrument, pitch, duration))
		self.state.addProgramChange(self.track,channel, self.time, instrument)
		self.state.addNote(0,channel,pitch,self.time,duration,volume)

		self.time+=1

	def writeFile(self, savePath):
		""" Write the current state of the MIDI file to disk.

			savePath: Name+Path of the MIDI file to be saved.
		"""
		binfile = open(savePath, 'wb')
		self.state.writeFile(binfile)
		binfile.close()
Ejemplo n.º 11
0
def write_to_midifile(data, track_type='single', file='temp.mid'):
    """
    data: list of tuples of x, y coordinates for pitch and timing
          Optional: add a string to the start of the data list to specify instrument!
    type: the type of data passed to create tracks. Either 'single' or 'multiple'
    """
    if track_type not in ['single', 'multiple']:
        raise ValueError('Track type must be single or multiple')

    if track_type == 'single':
        data = [data]

    #memfile = io.BytesIO()
    realfile = open(file, 'wb')
    midifile = MIDIFile(numTracks=len(data), adjust_origin=False)

    track = 0
    time = 0
    program = 0
    channel = 0
    duration = 1
    volume = 90

    for data_list in data:
        midifile.addTrackName(track, time, 'Track {}'.format(track))
        midifile.addTempo(track, time, 60)

        instrument_type = 'melodic'
        if type(data_list[0]) != tuple:
            program, instrument_type = get_instrument(data_list.pop(0))

        if instrument_type == 'percussion':
            volume = 100
            channel = 9

        # Write the notes we want to appear in the file
        for point in data_list:
            time = point[0]
            pitch = int(point[1]) if instrument_type == 'melodic' else program
            midifile.addNote(track, channel, pitch, time, duration, volume)
            midifile.addProgramChange(track, channel, time, program)

        track += 1
        channel = 0

    midifile.writeFile(realfile)
    realfile.close()

    return file
Ejemplo n.º 12
0
    def testProgramChange(self):
        #import pdb; pdb.set_trace()
        program = 10
        channel = 0
        MyMIDI = MIDIFile(1)
        MyMIDI.addProgramChange(0, channel, 0, program)
        MyMIDI.close()

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

        self.assertEqual(MyMIDI.tracks[0].MIDIEventList[0].type,
                         'ProgramChange')
        self.assertEqual(data.unpack_into_byte(0), 0x00)  # time
        self.assertEqual(data.unpack_into_byte(1), 0xC << 4 | channel)  # Code
        self.assertEqual(data.unpack_into_byte(2), program)
Ejemplo n.º 13
0
def handle_score(score):
    parts = score.findall('part-list/score-part')
    midiparts = []
    for part in parts:
        actualpart = score.find('part[@id="%s"]' % part.get('id'))
        tuning = handle_tuning(actualpart)
        trackname = gettext(part.find('part-name'))
        midipart = MIDIFile(1)
        midipart.addTrackName(0, 0, trackname)
        midipart.name = trackname
        for channel, _ in enumerate(tuning):
            midipart.addProgramChange(0, channel, 0, getint(part.find('.//midi-program')))
        midipart.addTempo(0, 0, 120)
        handle_measures(midipart, actualpart, tuning)
        midiparts.append(midipart)
    return midiparts
Ejemplo n.º 14
0
def write_midi(filename, sequence):
    filename = "markov/"+filename
    midi = MIDIFile(1)
    track = 0
    start_time = 0
    midi.addTrackName(track, start_time, filename[:-4])
    tempo = random.randrange(360, 480)
    midi.addTempo(track, start_time, tempo)
    midi.addProgramChange(0, 0, 0, 1)
    
    for i in range(len(sequence)):
        note = sequence[i]
        midi.addNote(track, 0, note.pitch, note.time, note.duration, note.volume)
    f = open(filename, 'w')
    midi.writeFile(f)
    f.close()
Ejemplo n.º 15
0
def write_midi(filename, sequence):
    filename = "markov/" + filename
    midi = MIDIFile(1)
    track = 0
    start_time = 0
    midi.addTrackName(track, start_time, filename[:-4])
    tempo = random.randrange(360, 480)
    midi.addTempo(track, start_time, tempo)
    midi.addProgramChange(0, 0, 0, 1)

    for i in range(len(sequence)):
        note = sequence[i]
        midi.addNote(track, 0, note.pitch, note.time, note.duration,
                     note.volume)
    f = open(filename, 'w')
    midi.writeFile(f)
    f.close()
Ejemplo n.º 16
0
    def testProgramChange(self):
        program = 10
        channel = 0
        tracknum = 0
        realtracknum = tracknum
        time = 0.0
        MyMIDI = MIDIFile(1)
        if MyMIDI.header.numeric_format == 1:
            realtracknum = tracknum + 1
        MyMIDI.addProgramChange(tracknum, channel, time, program)
        MyMIDI.close()

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

        self.assertEqual(MyMIDI.tracks[realtracknum].MIDIEventList[0].evtname, 'ProgramChange')
        self.assertEqual(data.unpack_into_byte(0), 0x00)  # time
        self.assertEqual(data.unpack_into_byte(1), 0xC << 4 | channel)  # Code
        self.assertEqual(data.unpack_into_byte(2), program)
Ejemplo n.º 17
0
def setup_outputs():
    global midi_writer, video_writer

    if Config.show_preview_video:
        cv2.namedWindow(Config.preview_window_title)

    if Config.save_to_midi:
        midi_writer = MIDIFile(numTracks=1)
        midi_writer.addTrackName(Config.midi_track_index, 0, Config.midi_track_name)
        midi_writer.addTempo(Config.midi_track_index, 0, Config.midi_tempo)
        midi_writer.addProgramChange(Config.midi_track_index, 0, 0, program=0)  # 0: Acoustic Grand (https://pjb.com.au/muscript/gm.html)

    if Config.save_to_video:
        logger.info("Creating video writer")
        video_writer = cv2.VideoWriter(Config.output_video_file_name,
                                       cv2.VideoWriter_fourcc(*Config.output_video_codec),
                                       project_state.fps,
                                       project_state.frame_shape)
Ejemplo n.º 18
0
def write_to_midifile(data, track_type='single'):

    if track_type not in ['single', 'multiple']:
        raise ValueError('Track type must be single or multiple')

    if track_type == 'single':
        data = [data]

    memfile = io.BytesIO()
    midifile = MIDIFile(numTracks=len(data), adjust_origin=False)

    track = 0
    time = 0
    program = 0
    channel = 0
    duration = 1
    volume = 90

    for data_list in data:
        midifile.addTrackName(track, time, 'Track {}'.format(track))
        midifile.addTempo(track, time, 120)

        instrument_type = 'melodic'
        if type(data_list[0]) != tuple:
            program, instrument_type = get_instrument(data_list.pop(0))

        if instrument_type == 'percussion':
            volume = 100
            channel = 9

        # Write the notes we want to appear in the file
        for point in data_list:
            time = point[0]
            pitch = int(point[1]) if instrument_type == 'melodic' else program
            midifile.addNote(track, channel, pitch, time, duration, volume)
            midifile.addProgramChange(track, channel, time, program)

        track += 1
        channel = 0

    midifile.writeFile(memfile)

    return memfile
Ejemplo n.º 19
0
class Midi:
    """Musique midi"""
    def __init__(self, partition, titre, tempo):
        # Définition des paramètres MIDI.
        piste = 0
        temps = 0
        self.tempo = tempo / 2
        self.sortiemidi = MIDIFile(1, file_format=1)
        # Nom de la piste.
        self.sortiemidi.addTrackName(piste, temps, sansaccents(titre))
        # Tempo.
        self.sortiemidi.addTempo(piste, temps, self.tempo)
        # Instrument (74 : flûte).
        self.sortiemidi.addProgramChange(piste, 0, temps, 74)
        self.traiter_partition(partition, piste, temps)

    def traiter_partition(self, partition, piste, temps):
        """Création des évènements MIDI"""
        transposition = partition.transposition
        channel = 0
        volume = 127
        for mot in partition:
            for i, syllabe in enumerate(mot):
                syl = str(syllabe)
                if i + 1 < len(mot):
                    syl = syl + '-'
                for j, note in enumerate(notes for notes in syllabe.musique
                                         if isinstance(notes, Note)):
                    pitch = note.hauteur + transposition
                    duree = int(note.duree)
                    self.sortiemidi.addTempo(piste, temps,
                                             (self.tempo * duree / note.duree))
                    self.sortiemidi.addNote(piste, channel, pitch, temps,
                                            duree / 2, volume)
                    if j == 0:
                        self.sortiemidi.addText(piste, temps, syl)
                    temps += duree / 2

    def ecrire(self, chemin):
        """Écriture effective du fichier MIDI"""
        with (open(sys.stdout.fileno(), 'wb') if chemin == '-' else open(
                chemin, 'wb')) as sortie:
            self.sortiemidi.writeFile(sortie)
Ejemplo n.º 20
0
def main():
    prefix = os.getcwd() + '\\samples\\'
    parser = argparse.ArgumentParser()
    parser.add_argument('filename', help='the name of the image file')
    args = parser.parse_args()
    filename = args.filename
    while filename != 'quit()':
        try:
            filename = prefix + filename
            pixels = get_pixels(filename)
            pixels88 = normalize_height(pixels)
            colors = get_colors(pixels88)
            print colors
            if len(colors) > 15:
                raise ColorException()
            break
        except IOError:
            print 'File not found. Please enter a valid filename.'
            filename = raw_input(
                'Please enter the name of your image file (or type \'quit()\' to quit):\n')
        except ColorException:
            print 'This image has too many colors.'
            filename = raw_input(
                'Please enter the name of your image file (or type \'quit()\' to quit):\n')
    if filename == 'quit()':
        return

    midi = MIDIFile(len(colors))
    track = 0
    for color in colors:
        instrument = int((color[0]*100+color[1]*10+color[2]) / (28305/127))
        midi.addProgramChange(track, track, 0, instrument)
        colors[color] = create_masterlist(color, pixels88)
        convert_to_music(midi, colors[color], track, tempo=240)
        track += 1
        #print `color` + ': ' + `instrument`
    # filename = 'beautiful_' + filename
    filename = filename.split('.')[0]
    binfile = open(filename + ".mid", 'wb')
    midi.writeFile(binfile)
    binfile.close() # no idea if this is necessary or not
Ejemplo n.º 21
0
def generate(n, program, suffix):
	MyMIDI = MIDIFile(2)
	track = 0   
	time = 0
	MyMIDI.addTrackName(track,time,"Test")
	MyMIDI.addTempo(track,time,30)
	track = 0
	channel = 0
	time = 0
	duration = 1.5
	volume = 100
	MyMIDI.addProgramChange(track, channel, 0, program)
	MyMIDI.addNote(track,channel, plist[n], 0,duration,volume)
	binfile = open("output.mid", 'wb')
	MyMIDI.writeFile(binfile)
	binfile.close()

	os.system("fluidsynth /usr/share/sounds/sf2/FluidR3_GM.sf2 output.mid -F output.wav --sample-rate 1000")
	os.system("lame -V 7 output.wav sound%d%s.mp3" % (n, suffix))
	os.system("rm output.mid")
	os.system("rm output.wav")
Ejemplo n.º 22
0
def build_midi_file(bpm, tracks):
    midif = MIDIFile(len(tracks))
    channel = 0
    print("%d tracks" % (len(tracks)))
    thistrack = 0
    for track in tracks:
        track_name = track.attrib["name"]
        midif.addTrackName(thistrack, 0, track_name)
        midif.addTempo(thistrack, channel, bpm)
        midif.addProgramChange(thistrack, channel, 0, 0)
        print("adding track ", track_name)
        for p in track.iter('pattern'):
            tstart = float(p.attrib['pos']) / DIV
            for note in p.findall('note'):
                attr = dict([(k, float(v)) for (k, v) in note.attrib.items()])
                key = int(attr['key'])
                dur = attr['len'] / DIV
                time = tstart + attr['pos'] / DIV
                vol = attr['vol']
                if dur <= 0 or vol <= 0 or time < 0: continue
                #print(">> adding note key %d @ %0.2f for %0.2f" %(key, time, dur))
                assert (0 <= key <= MAX_VEL)
                assert (dur > 0)
                vol = min(vol, MAX_VEL)
                midif.addNote(track=thistrack,
                              channel=channel,
                              pitch=key,
                              time=time,
                              duration=dur,
                              volume=vol)
        thistrack += 1

        # increments channel - avoids drumkit channel (channel #9)
        channel += 1
        if channel is 9:
            channel = 10
        if channel is 16:
            channel = 0

    return midif
Ejemplo n.º 23
0
def contours_to_sounds(all_init_notes, all_contours, keys, moods):
    # len of moods must be same as other lists! NOT CHECKED!
    # ALSO not checked value!
    # mood: 1 - happy, 0 - neutral, -1 - sad, -2 - sudden sad
    # right now: 1 == 0 and -1 == -2

    l = len(all_init_notes)

    duration = 1
    tempo = 120
    base_volumn = 100
    time = 0
    track = 0
    channel = 0
    vol = 100

    for i in range(l):
        outfile_name = EXP_DIR + str(i) + '.mid'
        # generate dir if not exists! TODO

        init_note = all_init_notes[i]
        contours = all_contours[i]
        rel_scale = get_rel_scale(moods[i])
        key = keys[i]
        notes = get_notes(init_note, contours, rel_scale, key)

        MyMIDI = MIDIFile(1, adjust_origin=None)
        MyMIDI.addTempo(track, time, tempo)

        # MyMIDI.addProgramChange(track=0, channel=0, time=time, program=40)
        MyMIDI.addProgramChange(track=0, channel=0, time=time, program=1)

        t_inc = 0
        for note in notes:
            t_inc += 1
            MyMIDI.addNote(track, channel, note, time + t_inc, duration, vol)

        with open(outfile_name, 'wb') as output_file:
            MyMIDI.writeFile(output_file)
Ejemplo n.º 24
0
class Midi_lib_interface:
    def __init__(self, numberTracks, track, bpm, time):
        self.mf = MIDIFile(numberTracks)
        self.mf.addTrackName(track, time, str(track))
        self.mf.addTempo(track, time, bpm)

    # Adiciona uma trilha de som
    def addTrack(self, track, time, tempo):
        self.mf.addTempo(track, time, tempo)
        self.mf.addTrackName(track, time, str(track))

    def addNote(self, track, channel, pitch, time, duration, volume):
        self.mf.addNote(track, channel, pitch, time, duration, volume)

    def addTempo(self, track, time, bpm):
        self.mf.addTempo(track, time, bpm)

    def changeInstrument(self, track, channel, time, instrument):
        self.mf.addProgramChange(track, channel, time, instrument)

    def save(self, musicName):
        with open("./musicas/" + musicName + ".mid", 'wb') as outf:
            self.mf.writeFile(outf)
Ejemplo n.º 25
0
    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"
            )
Ejemplo n.º 26
0
def init(parent):
    global sp_midi, chord_count, bass_count, melody_count, drums_count

    chord_count = 0
    bass_count = 0
    melody_count = 0
    drums_count = 0    

    sp_midi = MIDIFile(5)
    time = 0

    sp_midi.addTrackName(mixer.channels["drums"], time, "Drums")
    sp_midi.addProgramChange(mixer.channels["drums"], 10, 0, 118)

    sp_midi.addTrackName(mixer.channels["bass"], time, "Bass")
    sp_midi.addProgramChange(mixer.channels["bass"], mixer.channels["bass"], 0, 34)    

    sp_midi.addTrackName(mixer.channels["chords"], time, "Chords")
    sp_midi.addProgramChange(mixer.channels["chords"], mixer.channels["chords"], 0, 88)

    sp_midi.addTrackName(mixer.channels["melody"], time, "Melody")
    sp_midi.addProgramChange(mixer.channels["melody"], mixer.channels["melody"], 0, 26)
    print performer.bpm
    sp_midi.addTempo(0,0,parent.user_tempo)
Ejemplo n.º 27
0
class MidiWorld():
  """
  " Define MIDI class
  "
  " 1. read numbered notation file, the notation file should follow the format shown below
  " 2. write MIDI file
  """
  def __init__(self, note_file):
    self.volume = 100
    self.channel = 0
    self.note_file = note_file
    self.set_note_list()
    self.set_track_info()
    #===== Initiate MIDI file object with n_track tracks =====#
    self.mf = MIDIFile(self.n_track)
    # mf.addTrackName(track, time, "Sample Track")


  def set_note_list(self):
    #===== Get note list from the notation file =====#
    with open(self.note_file) as nf:
      note_str = nf.read().replace('\n', ' ')

    self.note_list = re.split('\s+', note_str)


  def set_track_info(self):
    #===== Set number of tracks and their time =====#
    ## number of tracks or channels, here we set the two numbers the same
    self.n_track = int(self.note_list[0])
    ## set time for each track
    self.track_time = [0]*self.n_track
    ## set track program
    self.program = [int(x) for x in self.note_list[1:self.n_track+1]]

    #===== Get tracks, the track section is contained within {} =====#
    ## Get track sections
    self.ltc_ind = [i for i, x in enumerate(self.note_list) if x == '{']
    self.rtc_ind = [i for i, x in enumerate(self.note_list) if x == '}']
    if len(self.ltc_ind) != len(self.rtc_ind):
      print '{ and } should be pair matched.'
      sys.exit()
    ## Get tracks
    self.track = [[] for x in range(self.n_track)]

    for lind, rind in zip(self.ltc_ind, self.rtc_ind):
      track_number = int(self.note_list[lind-1])
      self.track[track_number] += self.note_list[lind+1:rind]

    ## Get the total number of track sections
    # self.n_track_section = len(self.ltc_ind)
    ## Get every track number from the track sections,
    ## len(track_number_list) = n_track
    # self.track_number_list = list()
    # for i in range(self.n_track_section):
    #   self.track_number_list.append(int(self.note_list[self.ltc_ind[i]-2]))


  def write_track(self, track_number):
    """
    " write to track and channel
    """
    #===== Get the track list =====#
    track = self.track[track_number]

    channel_number = track_number

    #===== Set program (instrument) for the channel =====#
    self.mf.addProgramChange(track_number, channel_number, self.track_time[track_number], self.program[track_number])

    #===== Find every piece contained by paired [] =====#
    lp_ind = [i for i, x in enumerate(track) if x == '[']
    rp_ind = [i for i, x in enumerate(track) if x == ']']
    if len(lp_ind) != len(rp_ind):
      print '[ and ] should be pair matched.'
      sys.exit()

    for p in range(len(lp_ind)):
      #===== Tempo and major symbol are before the '[' =====#
      tempo = int(track[lp_ind[p]-2])
      self.mf.addTempo(track_number, self.track_time[track_number], tempo)

      major = track[lp_ind[p]-1]
      major_pitch = note_to_pitch(major)

      #===== Resolve every note =====#
      for s in track[lp_ind[p]+1:rp_ind[p]]:
        pitch, beat = numnote_resolve(s)
        if pitch != 999:  # if it is not break note (0)
          self.mf.addNote(track_number, channel_number,
                          major_pitch+pitch, self.track_time[track_number], beat, self.volume)

        self.track_time[track_number] += beat

  def write_midifile(self, output_midi_file):
    #===== write to each channel =====#
    for itc in range(self.n_track):
      print 'itc:', itc
      self.write_track(itc)

    #===== write it to disk =====#
    with open(output_midi_file, 'wb') as outf:
      self.mf.writeFile(outf)
Ejemplo n.º 28
0
def mark():

    ############################################################################
    # Setup Constants
    ############################################################################
    RED_CHANNEL = 0
    GREEN_CHANNEL = 1
    BLUE_CHANNEL = 2

    if args.channels is None:
        CHANNELS = [RED_CHANNEL,GREEN_CHANNEL,BLUE_CHANNEL]
    else:
        CHANNEL_CODES = {'r': RED_CHANNEL, 'g': GREEN_CHANNEL, 'b': BLUE_CHANNEL}
        CHANNELS = [CHANNEL_CODES[code] for code in args.channels]
    # # CHANNELS = [RED_CHANNEL]
    # CHANNELS = [BLUE_CHANNEL]
    # # CHANNELS = [GREEN_CHANNEL]

    ROOT_NOTE = 60
    MIDI_MIN = 24
    MIDI_MAX = 108
    RANGE = MIDI_MAX - MIDI_MIN

    REST_CHANCE = 0.1

    ############################################################################
    # Image data setup
    ############################################################################
    # Open the image file and read the RGB pixel values into an array
    im = Image.open(args.input, 'r')
    width, height = im.size
    pixel_values = list(im.getdata())
    pixel_values = pixel_values[:1000]


    ############################################################################
    # Setup MIDI Jawns
    ############################################################################
    # Create the MIDIFile Object
    MyMIDI = MIDIFile(1)
    # Add track name and tempo
    track = 0
    time = 0.0
    MyMIDI.addTempo(track,time, 113)
    MyMIDI.addTrackName(track,time,"Music Jawns")

    # RED: Chromatic Procussion
    MyMIDI.addProgramChange(track,RED_CHANNEL,time, 10)

    # GREEN: Brass
    MyMIDI.addProgramChange(track,GREEN_CHANNEL,time, 60)

    # BLUE: Brass
    MyMIDI.addProgramChange(track,BLUE_CHANNEL,time, 1)


    ############################################################################
    # Calculate the things!
    ############################################################################
    # Initialize our running RGB data values
    prevs = [0,0,0] # Previous R,G, and B values
    prev_lengths = [0,0,0] # Number of previous jawns at those values
    values = [[],[],[]] # When a new value is found, the old value and the count get added here

    # Calculate the running sums for R/G/B
    for pixel in pixel_values:
        for channel in CHANNELS:
            dis_pixel = pixel[channel] % RANGE
            if prevs[channel] == dis_pixel:
                # If this pixel value for the color is equal to
                # the last color, increment the count
                prev_lengths[channel] += 1
            else:
                # Otherwise, store the conut and reset the value
                store = (prevs[channel],prev_lengths[channel])
                values[channel].append(store)
                prevs[channel] = dis_pixel
                prev_lengths[channel] = 0

    # Remove timeless jawns
    for channel in CHANNELS:
        values[channel] = filter(lambda (value,count): count > 0, values[channel])


    values_short = [l[:10] for l in values]
    print values_short


    # Add a note. addNote expects the following information:
    channel = RED_CHANNEL
    start_pitch = ROOT_NOTE
    volume = 100

    for channel in CHANNELS:
        time = 0.0

        #  Get an iterator and skip the first val
        iterator = iter(values[channel])

        # We change these on each loop
        prev_val = next(iterator)[0]
        prev_pitch = start_pitch

        for (value,count) in values[channel]:
            # Find the current pitch
            diff = value - prev_val
            pitch = prev_pitch + diff

            if pitch < MIDI_MIN or pitch > MIDI_MAX:
                pitch = random.randint(MIDI_MIN,MIDI_MAX)

            # Update the previous vars
            prev_pitch = pitch
            prev_val = value

            # duration = math.log(count, random.randint(2,10))
            duration = count
            time = time + 1

            # If we didn't randomize to a rest, add the note
            if random.random() > REST_CHANCE:
                print "P: {}, T: {}, D: {}, V: {}".format(pitch,time,duration,volume)

                # Depending how big the value jump was, use a major chord, minor
                # chord, or single note
                if diff > 5:
                    pitch_set = major_chord(pitch)
                elif diff > 2:
                    pitch_set = minor_chord(pitch)
                else:
                    pitch_set = [pitch]

                for pitch in pitch_set:
                    MyMIDI.addNote(track,
                        channel,
                        pitch,
                        time,
                        duration,
                        volume)
            else:
                print "Resting - {}".format(channel)


    # print values
    # import ipdb; ipdb.set_trace()

    # Also write it to memory
    memFile = StringIO()
    MyMIDI.writeFile(memFile)

    # Use pygame to play the midi that we stored in memory (in memFile)
    pygame.init()
    pygame.mixer.init()
    memFile.seek(0)  # THIS IS CRITICAL, OTHERWISE YOU GET THAT ERROR!
    pygame.mixer.music.load(memFile)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        sleep(1)
Ejemplo n.º 29
0
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()
Ejemplo n.º 30
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)
Ejemplo n.º 31
0
def save_midi(pitches, tempo, rois, file_name):

    # Create the MIDIFile Object with x tracks
    MyMIDI = MIDIFile(len(rois))


    for i in range(len(rois)):
        # Tracks are numbered from zero. Times are measured in beats.
        track = i   
        time = 0
        # Add track name and tempo.
        MyMIDI.addTrackName(track,time,str(i))
        MyMIDI.addTempo(track,time,120)
        MyMIDI.addProgramChange(track,0, time, rois[i]['instrument'])

        pitch_roi = pitches[:,rois[i]['id']]

        tempo_roi = tempo[:,rois[i]['id']]

        total_time = 0

        print '- - - - - - - - - - - ', rois[i]['id'], '- - - - - - - - - - - ' 

        for j in range(len(pitches)):

            channel = 0
            pitch = pitch_roi[j]
            # if j > 0:
            #     pitch -= 12
            time = total_time
            print j, tempo_roi[j]
            duration = 0.5 / float(tempo_roi[j])
            print duration
            volume = 100
            total_time += duration

            print 'pitch:', pitch, 'time:', time, 'duration:', duration, 'tempo:', tempo_roi[j]

            #set volume. the solo is always higher
            if rois[i]['solo']:
                if tempo_roi[j] ==1:
                    volume = 100
                elif tempo_roi[j] == 2:
                    volume = 80
                elif tempo_roi[j] == 4:
                    volume = 75
                else:
                    volume = 50
            else:
                if tempo_roi[j] ==1:
                    volume = 70
                elif tempo_roi[j] == 2:
                    volume = 50
                elif tempo_roi[j] == 4:
                    volume = 45
                else:
                    volume = 20

            # Now add the note.
            MyMIDI.addNote(track,channel,pitch,time,duration, volume)



    # And write it to disk.
    binfile = open(file_name, 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
    print 'file', file_name, 'saved.'
Ejemplo n.º 32
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)
Ejemplo n.º 33
0
mf.addTrackName(track1, time1, "Human Population Growth")
mf.addTempo(track1, time1, 150)
mf.addTrackName(track2, time2, "El Nino")
mf.addTempo(track2, time2, 150)

#set other midi parameters here.
duration1 = 4
duration2 = 0.333
volume1 = 100
volume2 = 70
channel = 0

program1 = 42
program2 = 1
mf.addProgramChange(track1, channel, time1, program1)
mf.addProgramChange(track2, channel, time2, program2)

for j in range(0, len(pitch_human)):
    pitch1 = pitch_human[j]
    mf.addNote(track1, channel, pitch1, time1, duration1,
               volume1)  #adds information for each note
    time1 = time1 + 4

for j in range(0, len(pitch_elnino)):
    pitch2 = pitch_elnino[j]
    mf.addNote(track2, channel, pitch2, time2, duration2,
               volume2)  #adds information for each note
    time2 = time2 + 0.333

# write it to disk
Ejemplo n.º 34
0
    def generate(self, output):
        """Generate music using acctual state of object."""
        # general
        random.setstate(self.randomStates[0])
        generatedNotesPerBar = coalesce(self.notesPerBar, random.randint(1, 8))
        generatedNumberOfBassLines = coalesce(self.numberOfBassLines,
                                              random.randint(0, 2))
        generatedNumberOfMelodyLines = coalesce(self.numberOfMelodyLines,
                                                random.randint(0, 2))
        generatedTempo = coalesce(self.tempo, random.randint(80, 220))
        genertedPitch = coalesce(self.basePitch, random.randint(48, 72))

        # chord line
        random.setstate(self.randomStates[1])
        chordLine = GenerateChordsLine(
            GenerateChordsGroupsLine(
                coalesce(self.motiveLength, random.randint(1, 6))))
        genertaedMotiveLength = len(chordLine)
        chordLine *= coalesce(self.musicLength, random.randint(1, 4))
        lines = []

        # bass
        random.setstate(self.randomStates[2])
        for i in range(generatedNumberOfBassLines):
            nextRandomSet = random.randint(0, len(self.randomStates) - 1)
            if len(self.bassLinesOptions) > i:
                if self.bassLinesOptions[i] is None:
                    self.bassLinesOptions[i] = BassGenerator()
            else:
                self.bassLinesOptions.append(BassGenerator())
            lines.append(self.bassLinesOptions[i].generate(
                chordLine, genertaedMotiveLength, generatedNotesPerBar,
                genertedPitch))
            random.setstate(self.randomStates[nextRandomSet])

        # melody
        random.setstate(self.randomStates[3])
        for i in range(generatedNumberOfMelodyLines):
            nextRandomSet = random.randint(0, len(self.randomStates) - 1)
            if len(self.melodyLinesOptions) > i:
                if self.melodyLinesOptions[i] is None:
                    self.melodyLinesOptions[i] = MelodyGenerator()
            else:
                self.melodyLinesOptions.append(MelodyGenerator())
            lines.append(self.melodyLinesOptions[i].generate(
                chordLine, genertaedMotiveLength, generatedNotesPerBar,
                genertedPitch))
            random.setstate(self.randomStates[nextRandomSet])

        # Percussion
        # MakeMidi
        random.setstate(self.randomStates[5])
        # chordLine *= coalesce(self.musicLength, random.randint(1, 4))
        genertaedMusicLength = len(chordLine)
        MyMIDI = MIDIFile(1 + generatedNumberOfBassLines +
                          generatedNumberOfMelodyLines)
        volume = 200 // (
            (2 + generatedNumberOfBassLines + generatedNumberOfMelodyLines) //
            2)
        MyMIDI.addTrackName(0, 0, "ChordLine")
        MyMIDI.addTempo(0, 0, generatedTempo)
        MyMIDI.addProgramChange(
            0, 0, 0,
            coalesce(self.chordInstrument,
                     random.choice(list(chain(pI.Guitar, pI.Piano)))))
        for i, chord in enumerate(chordLine):
            for x in chord:
                MyMIDI.addNote(0, 0, x + genertedPitch,
                               i * generatedNotesPerBar + 1,
                               generatedNotesPerBar, volume)

        random.setstate(self.randomStates[6])
        for i, line in enumerate(lines):
            nextRandomSet = random.randint(0, len(self.randomStates) - 1)
            addLineToTrack(MyMIDI, i + 1, 0, line,
                           genertaedMusicLength * generatedNotesPerBar,
                           generatedNotesPerBar, volume)
            MyMIDI.addTrackName(i + 1, 0, "Track" + str(i + 1))
            MyMIDI.addTempo(i + 1, 0, generatedTempo)
            random.setstate(self.randomStates[nextRandomSet])

        binfile = open(output, 'wb')
        MyMIDI.writeFile(binfile)
        binfile.close()
Ejemplo n.º 35
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!'
Ejemplo n.º 36
0
'''Generates a MIDI file with 12 random notes in C major, using the midiutil module. The instrument is also picked randomly. The result is then played with the sound.MIDIPlayer class.
If nothing happens, make sure that your device isn't muted.
'''

from midiutil.MidiFile import MIDIFile
from random import choice, randint
import sound

# Configure a MIDI file with one track:
midi = MIDIFile(1)
midi.addTempo(0, 0, 180)

# Select a random instrument:
program = randint(0, 255)
midi.addProgramChange(0, 0, 0, program)

# Generate some random notes:
duration = 1
c_major = [60, 62, 64, 65, 67, 69, 71]
for t in range(12):
	pitch = choice(c_major)
	# track, channel, pitch, time, duration, volume
	midi.addNote(0, 0, pitch, t * duration, duration, 100)
	
# Write output file:
with open('output.mid', 'w') as f:
	midi.writeFile(f)

# Play the result:
player = sound.MIDIPlayer('output.mid')
player.play()
Ejemplo n.º 37
0
class Music:
    """
    Class that manage the channels, instruments,
        notes and composes the music in general
    """
    def __init__(self,
                 name='sample',
                 notes=[],
                 bpm=120,
                 instrument=Instrument("Piano", 1),
                 volume=100,
                 octave=4,
                 actual_time=0):
        self.actual_time = actual_time
        self.instrument = instrument
        self.octave = octave
        self.name = name
        self.notes = notes
        self.bpm = bpm
        self.volume = volume
        self.midi_file = MIDIFile(1)

    def generate(self):
        """ Generate a temporary midi_file for the music"""
        track = 0  #Only track
        time = 0  #Start at the beginning
        self.midi_file.addTrackName(track, time, self.name)
        self.midi_file.addTempo(track, time, self.bpm)

        channel = 0
        duration = 1

        for i, note in enumerate(self.notes):
            print(note)
            current_instrument = note.instrument
            if i > 0:
                old_instrument = self.notes[i - 1].instrument
            else:
                old_instrument = current_instrument

            if old_instrument != current_instrument:
                self.midi_file.addProgramChange(track, channel, i * 2,
                                                current_instrument)

            self.midi_file.addNote(track, channel,
                                   note.midi_number * note.octave, i * 2,
                                   duration, note.volume)

        file_name = "../temp/" + self.name + ".mid"
        with open(file_name, 'wb') as out:
            self.midi_file.writeFile(out)

    def adjust_instrument(self, parameter=1, option='set'):
        """  Adjust the main instrument of the music"""
        self.instrument.midi_number = adjust(self.instrument.midi_number,
                                             parameter, option)

    def add_note(self, note):
        """ Add a note to the music stream, so it can be played"""
        note = int(note)
        note_volume = self.volume
        if note >= 23:
            note = 23
        elif note <= 12 and note > 0:
            note = 12
        elif note == 0:
            note_volume = 0
        else:
            note_volume = 0

        current_instrument = self.instrument.midi_number
        self.notes.append(
            Note('', int(note), self.octave, current_instrument, note_volume))

    def add_random_note(self, minimum=12, maximum=23):
        """ Add a random note in the music strem"""
        if minimum < 12:
            minimum = 12
        elif maximum > 23:
            maximum = 23
        elif minimum > maximum:
            minimum = maximum

        note_number = rng.randint(min, max)
        self.add_note(note_number)

    def adjust_octave(self, parameter=1, option='set'):
        """ Adjust the octave of the music"""
        self.octave = adjust(self.octave, parameter, option)
        if self.octave > 8:
            self.octave = 8
        elif self.octave < 0:
            self.octave = 0

    def adjust_volume(self, parameter=1, option='double'):
        """ Adjust the volume of the music"""
        self.volume = adjust(self.volume, parameter, option)
        if self.volume > 127:
            self.volume = 127
        elif self.volume < 0:
            self.volume = 0

    def adjust_bpm(self, parameter=1, option='set'):
        """ Adjust the bpm of the music"""
        self.bpm = adjust(self.bpm, parameter, option)
Ejemplo n.º 38
0
def makeAndPlaySong(inString):

    #Code to Get Numbers from URL
    try:
        url = inString.split('//')[1]
        urldotsplit = url.split('.', 2)
        domain = urldotsplit[1]
        afterdomain = urldotsplit[2]
        afterdomainsplit = afterdomain.split('/')
        domainsuffix = afterdomainsplit[0]
        path = afterdomainsplit[1]
    except:
        try:
            url = inString.split('//')[1]
            urldotsplit = url.split('.', 2)
            domain = urldotsplit[1]
            domainsuffix = urldotsplit[2]
            path = ''
            print('Using Vanilla Url')
        except:
            try:
                url = inString.split('//')[1]
                urldotsplit = url.split('.', 1)
                domain = urldotsplit[0]
                domainsuffix = urldotsplit[1]
                path = ''
                print('Using Vanilla Url that has no www.')
            except:
                print('Invalid Url, resorting to failsafe')
                domain = inString[:8]
                domainsuffix = inString[8:11]
                path = inString[11:]

    domainnum = str(int.from_bytes(str.encode(domain), byteorder='little') * 5)
    domainsuffixnum = str(
        int.from_bytes(str.encode(domainsuffix), byteorder='little') * 5)
    pathnum = str(int.from_bytes(str.encode(path), byteorder='little') * 5)
    #print(domainnum)
    #print(domainsuffixnum)
    print('PathNum', pathnum)
    originaldomainnum = domainnum

    #Code to build Music using Numbers
    musicpath = '/home/pi/Jenme489y/qrcodereader/music/'
    fileloc = musicpath + domain + path + '.mid'

    #scales
    majorints = [0, 2, 4, 5, 7, 9, 11]
    harmminorints = [0, 2, 3, 5, 7, 8, 11]
    jazzints = [0, 3, 5, 6, 6, 7, 10]
    intervals = [majorints, harmminorints, jazzints]
    tempos = [40, 60, 80, 90, 100, 110, 120, 130, 150, 200]
    durations = [.25, .5, .5, 1, 1, 1, 1.5, 2, 2, 4]

    key = 60 + int(domainnum[0])  #key
    print('Key:', key)
    domainnum = domainnum[1:]
    interval = cyclicfind(int(domainnum[0]), intervals)  #scale
    print('Interval:', interval)
    domainnum = domainnum[1:]
    tempo = tempos[int(domainnum[0])]  #speed
    domainnum = domainnum[1:]
    melodyvoice = int(domainnum[0:2])  #instrument
    domainnum = domainnum[2:]

    mididata = MIDIFile(1)
    mididata.addTrackName(0, 0, 'Melody')
    mididata.addProgramChange(0, 0, 0, melodyvoice)
    mididata.addTempo(0, 0, tempo)

    notes = []
    notedurations = []
    totalduration = 8
    duration = 0
    priornoteindex = key
    #make the main phrase
    while (duration < totalduration):
        if (len(domainnum) < 4):
            domainnum = domainnum + originaldomainnum
        note, priornoteindex = getNote(int(domainnum[0:2]), priornoteindex,
                                       key, interval)
        notes.append(note)
        domainnum = domainnum[2:]
        noteduration = durations[int(domainnum[0])]
        if ((noteduration + duration) > totalduration):
            notes = notes[:(len(notes) - 1)]
            duration = totalduration
            break
        notedurations.append(noteduration)
        duration = duration + noteduration

    #addvarience of the path
    try:
        for i in range(len(pathnum) - 2):
            print(i)
            if int(pathnum[i]) == 0:
                mididata.addProgramChange(0, 0, 0, int(pathnum[i + 1]))
            elif int(pathnum[i]) < 5:
                notes[int(
                    pathnum[i +
                            1])] = notes[int(pathnum[i + 1])] - int(pathnum[i])
            elif int(pathnum[i]) < 9:
                notes[int(
                    pathnum[i +
                            1])] = notes[int(pathnum[i + 1])] + int(pathnum[i])
            else:
                mididata.addTempo(0, 0, tempos[int(pathnum[i + 1])])
    except:
        pass

    notestarttime = 0
    volume = 100
    for i in range(len(notes)):
        if (len(domainnum) < 2):
            domainnum = domainnum + originaldomainnum
        mididata.addNote(0,
                         0,
                         notes[i],
                         notestarttime,
                         notedurations[i],
                         (volume - 5 + int(domainnum[0]) * 2),
                         annotation=None)
        notestarttime = notestarttime + notedurations[i]
        domainnum = domainnum[1:]

    #Play Midi File
    if (os.path.isfile(fileloc)):
        pass
    fobject = open(fileloc, 'wb')
    mididata.writeFile(fobject)
    fobject.close()
    subprocess.call(['timidity', fileloc])
Ejemplo n.º 39
0
pitch = 64  # E4
time = 2  # start on beat 2
duration = 1  # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

pitch = 67  # G4
time = 4  # start on beat 4
duration = 1  # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

track = 0
time = 3  # Eight beats into the composition
program = 21  # A Cello

mf.addProgramChange(track, channel, time, program)

################
track = 1  # the only track

time = 5  # start at the beginning
tempo = 60  # In BPM
mf.addTrackName(track, time, "Track")
mf.addTempo(track, time, tempo)

# add some notes
channel = 0
volume = 100

pitch = 60  # C4 (middle C)
time = 5  # start on beat 0
Ejemplo n.º 40
0
#! python2

from midiutil.MidiFile import MIDIFile
import sound
import brainz
import time

original_speed = 100
# Configure a MIDI file with one track:
midi = MIDIFile(1)
midi.addTempo(0, 0, original_speed)

# Select a instrument:
program = 1
midi.addProgramChange(0, 0, 0, program)

# Generate some random notes:
duration = 1
# music = [57, 57, 57, 53, 60, 57, 53, 60, 57]
# music = [64, 63, 64, 63, 64, 59, 62, 60, 57]
# music = [56, 61, 64, 56, 61, 64, 56, 61, 64]

# music = [60, 64, 67, 72, 76, 67, 72, 76, 60, 62, 69, 74, 77, 69, 74, 77]
# music = [60, 55, 57, 59, 60, 62, 55, 55, 64, 60, 62, 64, 65, 67, 55, 55]
# music = [60, 62, 64, 65, 67, 69, 71, 72, 72, 71, 69, 67, 65, 64, 62, 60]

music = [
    60, 60, 60, 60, 59, 57, 59, 60, 62, 64, 64, 64, 64, 62, 60, 62, 64, 65, 67,
    60, 69, 69, 67, 65, 64, 62, 60, 59, 57, 55, 56, 57, 59, 60
]
# music = [60, 64, 67, 72, 76, 67, 72, 76, 60, 64, 67, 72, 76, 67, 72, 76, 60, 62, 69, 74, 77, 69, 74, 77, 60, 62, 69, 74, 77, 69, 74, 77]
Ejemplo n.º 41
0
x=(math.log(50))/72
z=(math.exp(10))/72
testmusic =wave.open(infile_loc_str,"rb")
music_params = testmusic.getparams()
nchannels,sampwidth,framerate,nframes = music_params[:4]

MyMIDI = MIDIFile(1,True)
# Tracks are numbered from zero. Times are measured in beats.
track = 0
time = 0
instrument = 1
        # Add track name and tempo.
MyMIDI.addTrackName(track,time,"Sample Track")
MyMIDI.addTempo(track,time,120)
MyMIDI.addProgramChange(track,0,time,instrument)

str_data = testmusic.readframes(nframes)
testmusic.close()
wave_data = np.fromstring(str_data,dtype=np.short)
wave_data.shape = -1,2
wave_data = wave_data.T
wave_datam = wave_data[0] 
nengliang = [0]*60
lengthofmusic = len(wave_data[0])
totaltimes = lengthofmusic
time_range = 441
times = totaltimes//time_range

tmp_array = [0]* times
tmp_array2 = [0]* times
Ejemplo n.º 42
0
    def testRemoveDuplicates(self):
        # First notes
        track = 0
        channel = 0
        pitch = 69
        time = 0
        duration = 1
        volume = 64
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(track, channel, pitch, time, duration, volume)
        MyMIDI.addNote(track, channel, pitch, time, duration, volume)
        MyMIDI.close()
        self.assertEqual(1, len(MyMIDI.tracks[1].eventList))  # One event
        MyMIDI = MIDIFile(1)
        MyMIDI.addNote(track, channel, pitch, time, duration, volume)
        pitch = 70
        MyMIDI.addNote(track, channel, pitch, time, duration, volume)
        MyMIDI.close()
        self.assertEqual(2, len(MyMIDI.tracks[1].eventList))  # Two events

        # Next tempo
        tempo = 60
        track = 0
        time = 0
        MyMIDI = MIDIFile(1)
        MyMIDI.addTempo(track, time, tempo)
        MyMIDI.addTempo(track, time, tempo)
        MyMIDI.close()
        self.assertEqual(1, len(MyMIDI.tracks[0].eventList))
        MyMIDI = MIDIFile(1)
        MyMIDI.addTempo(track, time, tempo)
        tempo = 80
        MyMIDI.addTempo(track, time, tempo)
        MyMIDI.close()
        self.assertEqual(2, len(MyMIDI.tracks[0].eventList))

        # Program Number
        time = 0
        track = 0
        program = 10
        channel = 0
        MyMIDI = MIDIFile(1)
        MyMIDI.addProgramChange(track, channel, time, program)
        MyMIDI.addProgramChange(track, channel, time, program)
        MyMIDI.close()
        self.assertEqual(1, len(MyMIDI.tracks[0].eventList))
        MyMIDI = MIDIFile(1)
        MyMIDI.addProgramChange(track, channel, time, program)
        program = 11
        MyMIDI.addProgramChange(track, channel, time, program)
        MyMIDI.close()
        self.assertEqual(2, len(MyMIDI.tracks[0].eventList))

        # Track Name
        track = 0
        time = 0
        track_name = "track"
        MyMIDI = MIDIFile(1)
        MyMIDI.addTrackName(track, time, track_name)
        MyMIDI.addTrackName(track, time, track_name)
        MyMIDI.close()
        self.assertEqual(1, len(MyMIDI.tracks[1].eventList))
        MyMIDI = MIDIFile(1)
        MyMIDI.addTrackName(track, time, track_name)
        track_name = "track 2"
        MyMIDI.addTrackName(track, time, track_name)
        MyMIDI.close()
        self.assertEqual(2, len(MyMIDI.tracks[1].eventList))

        # SysEx. These are never removed
        track = 0
        time = 0
        manufacturer = 10
        MyMIDI = MIDIFile(1)
        MyMIDI.addSysEx(track, time, manufacturer, struct.pack('>B', 0x01))
        MyMIDI.addSysEx(track, time, manufacturer, struct.pack('>B', 0x01))
        MyMIDI.close()
        self.assertEqual(2, len(MyMIDI.tracks[1].eventList))

        # UniversalSysEx. Same thing -- never remove

        track = 0
        time = 0
        code = 1
        subcode = 2
        payload_number = 47

        payload = struct.pack('>B', payload_number)
        MyMIDI = MIDIFile(1)
        MyMIDI.addUniversalSysEx(track,
                                 time,
                                 code,
                                 subcode,
                                 payload,
                                 realTime=True)
        MyMIDI.addUniversalSysEx(track,
                                 time,
                                 code,
                                 subcode,
                                 payload,
                                 realTime=True)
        MyMIDI.close()
        self.assertEqual(2, len(MyMIDI.tracks[1].eventList))
Ejemplo n.º 43
0

                time = count
                

                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')