Esempio n. 1
0
def writeMidiFromPredictions(predictions, sampleRate, sampleLength,  midiFileName = "predicted_notes.midi", minMIDINumber = 40, useNumberOfNotesInfo = True):
    print("Writing MIDI file...")
    tempo = 120 # bpm
    noteDurationInSec = float(sampleLength) / float(sampleRate)
    noteDurationInBeat = noteDurationInSec / 60.0 * tempo
    MyMIDI = MIDIFile(1)
    MyMIDI.addTempo(0,0, tempo)
    for i in range(predictions.shape[0]):
        numberOfNotesVector = predictions[i,0:3]
        pitchesVector = predictions[i,4:]
        pitches = set()
        if useNumberOfNotesInfo:
            numberOfNotes = np.argmax(numberOfNotesVector)
            for n in range(numberOfNotes):
                thisNote = np.argmax(pitchesVector)
                pitches.add(thisNote + minMIDINumber)
                pitchesVector[thisNote] = -1
        else:
            pitchesVector = np.round(pitchesVector)
            noteIndices = np.nonzero(pitchesVector)[0]
            for noteIndex in noteIndices:
                pitches.add(noteIndex + minMIDINumber)

        for pitch in pitches:
             MyMIDI.addNote(0,0,pitch,noteDurationInBeat*i,noteDurationInBeat,127)
    with open(midiFileName, "wb") as output_file:
        MyMIDI.writeFile(output_file)
Esempio n. 2
0
def toMidi(chord_prog):
    midi = MIDIFile(1)
    track = 0
    channel = 0
    time = 0
    duration = 2
    volume = 60

    for chord in chord_prog:  #iterate through chords in progression
        #  try:
        ch = Chord(chord)  #get pyChord object of chord
        # except:
        #ValueError("Sorry! Couln't parse complex chord! Try again :(")
        comps = ch.components()  #get chord components using pyChord
        for item in comps:
            pitch = NOTES[item]  #get each pitch
            midi.addNote(track,
                         channel,
                         pitch,
                         time,
                         duration,
                         volume,
                         annotation=None)  #add MIDI note
        time += 2

    with open(str(chord_prog) + ".mid", 'wb') as output_file:
        midi.writeFile(output_file)  #output to MIDI file
Esempio n. 3
0
def write_to_midi(song, filename, *tempo):
    track    = 0
    channel  = 0
    time     = 0   # In beats
    if not tempo:
        tempo    = 160 # In BPM
    else:
        tempo = tempo[0]
    volume   = 100 # 0-127, as per the MIDI standard

    MyMIDI = MIDIFile(1) # One track, defaults to format 1 (tempo track
                         # automatically created)
    MyMIDI.addTempo(track, time, tempo)

    for i in range(len(song)):
        if song[i][0] < 60:
            volume = 92
        elif song[i][0] < 50:
            volume = 86
        elif song[i][0] < 45:
            volume = 83
        else:
            volume = 100
        MyMIDI.addNote(track, channel, song[i][0], song[i][2],
                       Space_Values[song[i][1]], volume)


    with open(filename + ".mid", "wb") as output_file:
        MyMIDI.writeFile(output_file)
Esempio n. 4
0
def start():

    startingPitch = args.startingnote
    track = args.track
    channel = args.channel
    tempo = args.tempo
    volume = args.velocity
    time = args.time
    duration = args.duration

    formattedForInsert = formatDNAFile(args.sequence_file)
    myDegrees, mySpeeds = textToPitches(formattedForInsert, startingPitch)
    myDegrees, mySpeeds = findDifference(myDegrees, mySpeeds, startingPitch)
    myDegrees, mySpeeds = sixthTurnaround(myDegrees, mySpeeds, startingPitch)
    myDegrees, mySpeeds = afterSomeHalfs(myDegrees, mySpeeds, startingPitch)

    MyMIDI = MIDIFile(1, adjust_origin=True)  # One track
    MyMIDI.addTempo(track, time, tempo)
    currentTime = time
    for i, pitch in enumerate(myDegrees):
        MyMIDI.addNote(track, channel, pitch, currentTime, mySpeeds[i], volume)
        currentTime = currentTime + mySpeeds[i]

    with open("DNAmusic_" + timestamp + ".mid", "wb") as output_file:
        MyMIDI.writeFile(output_file)
Esempio n. 5
0
    def write_midi(self,name):
        """writes midi file for the piece"""
        time = 0
        MyMIDI = MIDIFile(1)
        MyMIDI.addTempo(track, time, tempo)
        
        for idea in self.ideas:
            for note in idea.melody:
                for pitch in note.pitch:
                    MyMIDI.addNote(track, channel, pitch, time, note.duration, volume)
                time += note.duration

        # adding bass
        time = 0
        for idea in self.ideas:
            for note in idea.bass:
                for pitch in note.pitch:
                    MyMIDI.addNote(track, channel+1, pitch, time, note.duration, volume)
                time += note.duration
        


        with open(f"{name}.mid", "wb") as output_file:
            MyMIDI.writeFile(output_file)
        print(f'Done! Midi file saved as "{name}.mid"')
Esempio n. 6
0
    def export_midi(self, fileName, pitches=[36, 38, 42]):
        # Create a MIDI file
        midi = MIDIFile(1, adjust_origin=True)

        # Add the tempo track
        midi.addTempo(0, 0, self.bpm)

        # Add the events as notes
        for event in self.events:
            # Calculate the time and duration (and other variables)
            channel = 9  # Because 0-15
            pitch = pitches[event[1]]
            time = event[0] / self.beatUnit
            duration = 1
            velocity = 100
            # Add the note
            midi.addNote(0, channel, pitch, time, duration, velocity)

        # Export the file
        try:
            # Open the file
            with open(fileName, "wb") as output:
                # Write the MIDI to the file
                midi.writeFile(output)
            return True
        except IOError:
            # Error, return False
            return False
Esempio n. 7
0
def generate_random_melody():
    degrees = [60, 62, 64, 65, 67, 69, 71, 72]  # MIDI note number
    track = 0
    channel = 0
    time = 0  # In beats
    durations = [0.5, 1, 2]  # In beats
    tempo = 150  # In BPM
    volume = 100  # 0-127, as per the MIDI standard

    MyMIDI = MIDIFile(
        1)  # One track, defaults to format 1 (tempo track is created
    # automatically)
    MyMIDI.addTempo(track, time, tempo)

    for i in range(10):
        duration = random.choice(durations)

        MyMIDI.addNote(track, channel, random.choice(degrees), time, duration,
                       volume)
        time += duration

    file = BytesIO()

    MyMIDI.writeFile(file)
    file.seek(0)
    return file
Esempio n. 8
0
def turnToMidi(musicls):
    midi = MIDIFile(1)
    track = 0
    time = 0
    channel = 0
    pitch = 0
    duration = 1
    volume = 100

    midi.addTrackName(track, time, "test")
    midi.addTempo(track, time, 60)
    music = []
    for i, pitch in enumerate(musicls):
        if pitch[1] == True:
            duration = 1 / 2
            midi.addNote(track, channel, pitch[0], time, duration, volume)
            time += 1 / 2
            music.append([pitch[0], 1 / 2])
        else:
            duration = 1
            midi.addNote(track, channel, pitch[0], time, duration, volume)
            time += 1
            music.append([pitch[0], 1])
    print(music)
    midi_file = open("mary.mid", 'wb')
    midi.writeFile(midi_file)
    midi_file.close()
Esempio n. 9
0
class midiExport:
    global __MyMIDI, track, channel, volume

    def __init__(self, tempo):
        self.track = 0
        self.channel = 10  # channel (drum standard)
        self.volume = 100  # volume
        self.__MyMIDI = MIDIFile(
            1
        )  # one track, defaults to format 1 (tempo track is created automatically)
        self.__MyMIDI.addTempo(self.track, 0, tempo)  # add tempo (bpm) to file

    def addNotes(
        self, durationList, midiNote
    ):  # this function adds notes one at a time, based on a durationList
        currentTime = 0  # start at position 0
        for duration in durationList:
            self.__MyMIDI.addNote(
                self.track, self.channel, midiNote, currentTime, .25,
                self.volume
            )  # add note (track, channel, MIDInumber, time, duration, volume)
            currentTime += duration  # move to next position

    def saveMidi(self, filename):
        with open(filename, "wb") as output_file:  # create empty file
            self.__MyMIDI.writeFile(output_file)  # write MIDIFile
            print()
            print("File saved as", filename)  # let user know it's done
Esempio n. 10
0
def createMidi(mappedKeys, fileName):
    track = 0
    channel = 0
    time = 0  # In beats
    duration = 1  # In beats
    tempo = 100  # In BPM
    volume = 100  # 0-127, as per the MIDI standard

    MyMIDI = MIDIFile(
        1, adjust_origin=True
    )  # One track, defaults to format 1 (tempo track is created automatically)
    MyMIDI.addTempo(track, time, tempo)

    for i, pitch in enumerate(mappedKeys):
        if (mappedKeys[i] != 00):
            if (len(mappedKeys) > i + 1):
                if (mappedKeys[i + 1] != 00):
                    MyMIDI.addNote(track, channel, pitch, time + i, duration,
                                   volume)
                else:
                    MyMIDI.addNote(track, channel, pitch, time + i,
                                   duration + 1, volume)
            else:
                MyMIDI.addNote(track, channel, pitch, time + i, duration,
                               volume)

    with open(meta.getRootDir() + '/MIDI_files/' + fileName + '.mid',
              "wb") as output_file:
        MyMIDI.writeFile(output_file)
Esempio n. 11
0
def convert_to_midi(piece: np.ndarray, name, resolution=1 / 4, tempo=60):
    midi_file = MIDIFile(1)
    midi_file.addTempo(0, 0, tempo)
    # keeps track of previous note to know if note is held
    previous_notes = list(piece[0])
    # keeps track of the duration the note has been held
    held_note_duration = [0] * len(piece[0])

    for t, notes in enumerate(piece):
        for i, note in enumerate(notes):
            if previous_notes[i] == note:
                held_note_duration[i] += resolution
            else:
                prev_note = previous_notes[i]
                # silent notes are nan
                if not (np.isnan(prev_note)):
                    time = t * resolution - held_note_duration[i]
                    midi_file.addNote(0, i, int(prev_note), time,
                                      held_note_duration[i], 100)
                # reset if new note
                held_note_duration[i] = resolution
                previous_notes[i] = note

    with open(f"{name}.mid", "wb") as output_file:
        midi_file.writeFile(output_file)
Esempio n. 12
0
 def play(self, n=10):
     # ligne suivante à changer avec un vérificateur
     # de présence de package en excluant try/except
     from midiutil import MIDIFile
     degrees = [60, 62, 64, 65, 67, 69, 71, 72]
     track = 0
     channel = 0
     time = 0
     duration = 1
     tempo = 120
     volume = 100
     morceau = MIDIFile(1)
     morceau.addTempo(track, time, tempo)
     #
     for i in range(n):
         j = i + self._rang_premier_terme
         terme = self.get_terme_rang(j)
         note = degrees[int(float(terme)) % len(degrees)]
         morceau.addNote(track, channel, note, time, duration, volume)
         time += 1
     #
     # à modifier si le fichier existe déjà
     # numérotation ou nom à spécifier en variable
     # optionnelle
     with open("temp.mid", "wb") as sortie:
         morceau.writeFile(sortie)
Esempio n. 13
0
def midi(scale, root=60, include_bass=True):
    from midiutil import MIDIFile

    track = 0
    channel = 0
    time = 0  # In beats
    duration = 1  # In beats
    tempo = 130  # In BPM
    volume = 120  # 0-127

    for mode in get_modes(scale):
        MyMIDI = MIDIFile(1)
        MyMIDI.addTempo(track, time, tempo)
        sequence = note_sequence(mode)

        if include_bass:
            MyMIDI.addNote(track, channel, root - 12, time, duration * 5,
                           volume)
            MyMIDI.addNote(track, channel, root - 12, time + 5, duration * 5,
                           volume)
            MyMIDI.addNote(track, channel, root - 12, time + 10, duration * 5,
                           volume)
            MyMIDI.addNote(track, channel, root - 12, time + 15, duration * 5,
                           volume)
            MyMIDI.addNote(track, channel, root - 12, time + 20, duration,
                           volume)

        for i, pitch in enumerate(sequence):
            MyMIDI.addNote(track, channel, root + pitch, time + i + 0.02,
                           duration, volume)

        filename = str(mode)[1:-1]
        out_file = filename + ".mid"
        with open(out_file, "wb") as output_file:
            MyMIDI.writeFile(output_file)
Esempio n. 14
0
    def runMido(self):
        mid = mido.MidiFile('./scripts/Magenta/SecondOutput/SecondOutput.mid')

        onOff = []
        notes = []
        time = []
        trackTime = 0
        program = 0
        tempo = 60

        MyMIDI = MIDIFile(1)
        MyMIDI.addProgramChange(0, 0, 0, self.program)
        MyMIDI.addTempo(0, 0, self.tempo)

        print("start")
        for msg in mid.play():
            onOff.append(msg.type)
            time.append(msg.time)
            test = msg.bytes()
            notes.append(test[1])
        print("finished")

        for i in range(0, len(notes)):
            MyMIDI.addNote(0, 0, notes[i], trackTime + time[i], 1, 100)
            trackTime += time[i]

        with open("static/audio/" + self.name + ".mid", "wb") as output_file:
            MyMIDI.writeFile(output_file)
Esempio n. 15
0
    def playMidi(self):
        list=self.listMyMIDI.get(0,END)
        length=len(list)
        MyMIDI = MIDIFile(length)
        listtrack=range(0,length)
        channel = 1
        listpitch = self.listPitchNum.get(0,END)
       # listtime = range(0,length)
        time = 0
        listduration = self.listDurOut.get(0,END)
        volume = 100

        for i in range (0,length):
            track = listtrack[i]
            channel = 1
            pitch = listpitch[i]
           # time = listtime[i]
            time = time + 1
            duration = listduration[i]
            volume = 100
            MyMIDI.addNote(track,channel,pitch,time,duration,volume)


   #     binfile = open("MyMIDI.mid",'wb')
    #    MyMIDI.writeFile(binfile)
     #   binfile.close()

        with open("MyMIDI.mid", "wb") as output_file:
            MyMIDI.writeFile(output_file)

        musicfile = open("MyMIDI.mid", 'rb')
        pygame.mixer.init()
        pygame.mixer.music.load(musicfile)
        pygame.mixer.music.play()
def save_genome_to_midi(filename: str, genome: Genome, num_bars: int,
                        num_notes: int, num_steps: int, pauses: bool, key: str,
                        scale: str, root: int, bpm: int):
    melody = genome_to_melody(genome, num_bars, num_notes, num_steps, pauses,
                              key, scale, root)

    if len(melody["notes"][0]) != len(melody["beat"]) or len(
            melody["notes"][0]) != len(melody["velocity"]):
        raise ValueError

    mf = MIDIFile(1)

    track = 0
    channel = 0

    time = 0.0
    mf.addTrackName(track, time, "Sample Track")
    mf.addTempo(track, time, bpm)

    for i, vel in enumerate(melody["velocity"]):
        if vel > 0:
            for step in melody["notes"]:
                mf.addNote(track, channel, step[i], time, melody["beat"][i],
                           vel)

        time += melody["beat"][i]

    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "wb") as f:
        mf.writeFile(f)
Esempio n. 17
0
    def writeSong(self, ascii_text):
        self.reset()
        MyMIDI = MIDIFile(16)
        MyMIDI.addTempo(0, 0, 120)
        MyMIDI.addProgramChange(4, 4, 0, 37)
        MyMIDI.addProgramChange(5, 5, 0, 38)

        ascii_text = self.getCountIn() + ascii_text
        trackCt = 0
        for lines in ascii_text.split("\n"):
            trackCt = 0

            print str(len(lines.split(","))) + ":" + lines + ":Track=" + str(
                trackCt) + ":Time=" + str(self.time)
            for note in lines.split(","):
                if note != "":
                    if (trackCt < 4):
                        channel = 9
                    else:
                        channel = trackCt
                    print "adding " + str(trackCt) + " " + str(
                        channel) + " " + str(note) + " " + str(
                            self.time) + " 1  127"
                    MyMIDI.addNote(trackCt, channel,
                                   int(note) - 1, self.time, 0.5, 127)
                trackCt = trackCt + 1

            if len(lines.split(",")) == 6:
                self.time = self.time + 0.25

        with open("myfilename.mid", "wb") as output_file:
            MyMIDI.writeFile(output_file)
Esempio n. 18
0
    def writefile(self, filepath):
        """
        Writes the current internal musical representation to the file
        specified by ``filepath``.
        """
        midi = MIDIFile(
            sum(1 for v in self.voices if v) + 1, True, True, True, 1)

        i = -1
        for vindex in range(len(self.voices)):
            voice = self.voices[vindex]
            if not voice:
                continue
            i += 1
            if i == 9: i += 1
            time = 0.0
            midi.addTempo(i, 0, self.tempo)
            midi.addProgramChange(i, i, 0, self.instruments[vindex])
            for note in voice:
                if note.pitch >= 0:
                    midi.addNote(i, i, note.pitch, time, note.duration,
                                 note.volume)
                time += note.duration

        time = 0.0
        midi.addTempo(9, 0, self.tempo)
        for note in self.drums:
            if note.pitch >= 0:
                midi.addNote(9, 9, note.pitch, time, note.duration,
                             note.volume)
            time += note.duration

        with open(filepath, "wb") as outputfile:
            midi.writeFile(outputfile)
Esempio n. 19
0
def write_midi(melody, id):
    old_pitch_list = melody.strip().split(' ')
    pitch_list = []
    for i in range(len(old_pitch_list)):
        if i % 2 == 0:
            pitch_list.append(old_pitch_list[i])
    # return pitch_list
    # create your MIDI object
    mf = MIDIFile(1)  # only 1 track
    track = 0  # the only track
    time = 0  # start at the beginning
    mf.addTrackName(track, time, "Sample Track" + str(id))
    mf.addTempo(track, time, 120)
    # add some notes
    channel = 0
    volume = 100
    for note in pitch_list:
        pitch = pitch_dict[note]
        duration = 1  # 1 beat long
        mf.addNote(track, channel, pitch, time, duration, volume)
        time += 2
    # write it to disk
    with open("/home/ubuntu/team15/midi/record/" + str(id) + '.txt',
              'w') as outtxt:
        for pitch in pitch_list:
            outtxt.write("%s\n" % pitch)
    midi_name = str(id) + ".mid"
    with open("/home/ubuntu/team15/midi/" + midi_name, 'wb') as outf:
        mf.writeFile(outf)
    return midi_name
Esempio n. 20
0
def backup_section(verses, tempo, key, volume_in):
    sectionMIDI = MIDIFile(1)
    sectionMIDI.addTempo(track, time, tempo)
    generate_track_from_source(sectionMIDI, 0, 8, verses[key][0],
                               verses[key][1], volume_in)
    with open("beat_file/" + key + ".mid", "wb") as output_file:
        sectionMIDI.writeFile(output_file)
Esempio n. 21
0
def timeSignatureOverlap():
    track = 0
    pitch = 60
    channel = 0
    time = 0  # In beats
    # duration = 1    # In beats
    tempo = 120  # In BPM
    volume = 100  # 0-127, as per the MIDI standard

    MyMIDI = MIDIFile(
        1)  # One track, defaults to format 1 (tempo track is created
    # automatically)
    MyMIDI.addTempo(track, time, tempo)

    howManyBeats = 16
    howManyDiffSamples = 4
    currPitch = 60

    for i in range(howManyBeats):
        time = i
        for count, numSubdivisions in enumerate([3, 4, 5, 7]):
            stepDuration = 1. / numSubdivisions
            for howMany in range(numSubdivisions):
                MyMIDI.addNote(track, channel, currPitch + count, time,
                               stepDuration, volume)
                time += stepDuration

    randomFileName = ''.join(
        random.choice(string.ascii_uppercase + string.ascii_lowercase +
                      string.digits) for _ in range(6)) + ".mid"

    with open("crazyMidiOutputs/overlap_" + randomFileName,
              "wb") as output_file:
        MyMIDI.writeFile(output_file)
Esempio n. 22
0
def save_melody_to_midi(melody, filename: str):

    if len(melody["notes"][0]) != len(melody["beat"]) or len(
            melody["notes"][0]) != len(melody["velocity"]):
        raise ValueError

    mf = MIDIFile(1)

    track = 0
    channel = 0

    time = 0.0
    mf.addTrackName(track, time, "Sample Track")
    mf.addTempo(track, time, bpm)

    for i, vel in enumerate(melody["velocity"]):
        if vel > 0:
            for step in melody["notes"]:
                mf.addNote(track, channel, step[i], time, melody["beat"][i],
                           vel)

        time += melody["beat"][i]
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "wb") as f:
        mf.writeFile(f)
Esempio n. 23
0
def render_midi(spec_path, o_path="", cycle_instr=False):
    with open(spec_path) as data:
        spec = json.load(data)
    
    tempo  = spec['bpm']
    tracks = spec['tracks']

    for idx, t in enumerate(tracks):
        nts = [(x + 1) + t['note_floor'] for x in t['notes']]
        midi_track = MIDIFile(1)
        note_dur = 4 / t['note_length']

        track_notes  = list(nts)
        track    = 0
        channel  = idx
        time     = note_dur
        duration = note_dur
        volume   = 127 if 'midi_volume' not in t.keys() else t['midi_volume']
        instrument = 1 if 'midi_instrument' not in t.keys() else t['midi_instrument']

        midi_track.addTempo(track, time, tempo)

        for i, pitch in enumerate(track_notes):
            if cycle_instr:
                instrument =  int(abs(math.sin((1/(len(track_notes))) * i)) * 127)

            midi_track.addProgramChange(track, channel, time * i, instrument)
            midi_track.addNote(track, channel, pitch, time * i, duration, volume)

        with open(o_path + '_-_Track 0' + str(idx+1)+".mid", "wb") as output_file:
            midi_track.writeFile(output_file)
Esempio n. 24
0
def send_sample():
    midiData = request.get_json()
    # To Do
    # Data should be validated before processed
    # The Midi File Creation should be in a separate function
    # Try/Catch Errors
    MyMIDI = MIDIFile(1)
    MyMIDI.addTempo(track, time, tempo)

    if isinstance(midiData, list):
        for i in range(0, len(midiData)):
            if midiData[i]:
                for pitch in midiData[i]:
                    print(track, channel, notes[pitch], i, duration, volume)
                    MyMIDI.addNote(track, channel, notes[pitch], i, duration,
                                   volume)

        with open("test.mid", "wb") as output_file:
            MyMIDI.writeFile(output_file)

        output_file.close()
        output_file.save('/Users/nigel/Documents/GitHub/test/backend/test.mid')

    else:
        console.log("Malformed Object")

    # return send_from_directory(app.config["CLIENT_MIDI"], filename = 'test.txt', as_attachment=True)
    # serve_static("abc")

    # p = "test.txt";
    # return send_file(p, as_attachment=True)
    return "{Processed: true}"
Esempio n. 25
0
def test(model, test_inputs, vocab):
    for j, piece in enumerate(test_inputs):
        input = []
        for t in range(50):
            input.append(vocab[str(piece[t])])
        input = tf.convert_to_tensor(input)

        beats = 80
        track = 0
        tempo = 60
        channel = 0
        duration = 1
        volume = 100

        generated = generate_piece(model, input, beats, vocab, tempo)
        midi = MIDIFile(1)
        midi.addTempo(track, beats, tempo)

        for i, pitches in enumerate(generated):
            pitches_array = pitches[1:-1].split(",")
            for pitch in pitches_array:
                try:
                    pitch_int = int(pitch)
                    midi.addNote(track, channel, pitch_int, i, duration,
                                 volume)
                except ValueError:
                    continue

        with open("./output/" + str(j) + ".mid", "wb") as output_file:
            print("Writing file {} of 25".format(j + 1))
            midi.writeFile(output_file)
Esempio n. 26
0
def write_midi(solo=None,
               chords=None,
               outfile="jazzy-bot-solo.mid",
               channel=0,
               tempo=220):
    """
		write a midi file based on solo, a list of Note objects, and chords, a
		list of chord objects
	"""
    assert (solo or chords)
    if solo and chords:
        midi = MIDIFile(2, adjust_origin=False)
        midi.addTempo(0, 0, tempo)
        write_midi_solo(midi, 0, solo, channel)
        write_midi_chords(midi, 1, chords, channel)
    else:
        midi = MIDIFile(1, adjust_origin=False)
        midi.addTempo(0, 0, tempo)
        if solo:
            write_midi_solo(midi, 0, solo, channel)
        elif chords:
            write_midi_chords(midi, 0, chords, channel)
    midi.addKeySignature(0, 0, 1, SHARPS, MAJOR)
    with open(outfile, "wb") as f:
        midi.writeFile(f)
Esempio n. 27
0
def generate_melody(length, root):
	#seed the randome number generator
	seed()

	base = int(root)
	len = int(length)
	#prepare a major scale array based off the root, C4 is 60
	notes = [base+0, base+2, base+4, base+5, base+7, base+9, base+11, base+12]

	degrees = []
	#generate a sequence of the length
	for i in range(0, len):
		degrees.append(notes[randint(0,7)])

	track    = 0
	channel  = 0
	time     = 0 #in beats
	duration = randint(1,4,len) #in beats 
	tempo    = 100 #in BPM
	volume   = 100 #0-127, as per the MIDI standard

	MyMIDI = MIDIFile(1) #one track, defaults to format 1(tempo track created auto)

	MyMIDI.addTempo(track,time,tempo)
	current = 0

	for i, pitch in enumerate(degrees):
		MyMIDI.addNote(track, channel, pitch, current, duration[i], volume)
		current = current + duration[i]

	with open("generated.mid", "wb") as output_file:
		MyMIDI.writeFile(output_file)
Esempio n. 28
0
def df_as_midi(df, tempo=120):
    """Converter dataframe to midi file expects columns time, pitchN, durationN, volumeN
    for N=0...15 (0 should be omitted)
    """
    track = 0
    time = df.time if "time" in df.columns else range(len(df))

    MyMIDI = MIDIFile(1)
    MyMIDI.addTempo(track, 0, tempo)

    for i, row in df.iterrows():
        t = time[i]
        for channel in range(15):
            N = "" if channel == 0 else str(channel)
            if f"pitch{N}" in df.columns:
                pitch = row[f"pitch{N}"]
                if pitch is not None:
                    duration = row[f"duration{N}"] if f"duration{N}" in row else 1
                    volume = row[f"volume{N}"] if f"volume{N}" in row else 100
                    MyMIDI.addNote(
                        track, channel, int(pitch), int(t), int(duration), int(volume)
                    )

    f = BytesIO()
    MyMIDI.writeFile(f)
    return f.getvalue()
Esempio n. 29
0
def melody_wav(tempo,key,instrument, chords):
    
    melody = melody_generator(key, chords)
    print(melody)
    track = 0
    channel = 0
    time = 0
    duration = 1
    tempo = tempo
    volume = 127

    midi = MIDIFile(1)

    midi.addTempo(track,time,tempo)

    for note in melody:
        print(note)
        if len(note) == 1:
            midi.addNote(track,channel,note[0],time,duration,volume)
            time+=1
        else:
            print(note[0], note[1])
            midi.addNote(track,channel,note[0],time,duration/2,volume)
            time+=0.5
            midi.addNote(track,channel,note[1],time,duration/2,volume)
            time+=0.5

    with open('midi/melody.mid', 'wb') as output_file:
        midi.writeFile(output_file)

    fs = FluidSynth(instrument)

    fs.midi_to_audio('midi/melody.mid', 'wav/melody.wav')

    lowpass('wav/melody.wav', 'wav/processed_melody.wav', 1200)
Esempio n. 30
0
def CreateDroneMidiFile(data_array, name):
    print("creating Drone " + name + " midi file")
    midiObj = MIDIFile(3)  # create one track
    midiObj.addTempo(0, 0, 150)

    #               track, channel, pitch, time      , duration      , volume
    midiObj.addNote(0, 0, 48, 0, len(data_array) / 4, 100)
    midiObj.addNote(1, 0, 55, 0, len(data_array) / 4, 100)
    midiObj.addNote(2, 0, 60, 0, len(data_array) / 4, 100)

    for i, pitch in enumerate(data_array):
        forward = i / 4
        ######## HIGH TONIC NOTE PITCHBEND ####################
        midiObj.addPitchWheelEvent(0, 0, forward,
                                   scale_and_randomize(pitch, 7000))

        ######## DOMINANT NOTE PITCHBEND ######################
        midiObj.addPitchWheelEvent(1, 0, forward,
                                   scale_and_randomize(pitch, 6000))

        #######  LOW TONIC NOTE PITCHBEND #####################
        # midiObj.addPitchWheelEvent(2, 0, note_division, scale_and_randomize(pitch))

    with open("midiFiles/" + name + ".mid", "wb") as midiFile:
        midiObj.writeFile(midiFile)