def playMIDI(x,counter,counter2, O):
    from midiutil.MidiFile import MIDIFile
    MyMIDI=MIDIFile(1, removeDuplicates=False, deinterleave=False)
    track=0
    time=0
    MyMIDI.addTrackName(track,time,"Sample")
    MyMIDI.addTempo(track,time,60)
    track=0
    channel=0
    a=North[x]
    b=East[x]
    c=West[x]
    averagex=round(((a+b+c)/3),0)
    pitchcalc=pitchnum(averagex)
    pitch=pitchcalc
    timecalc,O=deltatime(counter, O)
    time=2
    duration=timecalc
    if counter2==0:
        volume=10*(int(round(math.pow(North[x],1.0/3))))
    elif counter2==1:
        volume=10*(int(round(math.pow(East[x],1.0/3))))
    elif counter2==2:
        volume=10*(int(round(math.pow(West[x],1.0/3))))
    else:
        print("numcount error", counter2)
        volume=127
    MyMIDI.addNote(track,channel,pitch,time,duration,volume)
    outcount=str(counter)
    numcount=str(counter2)
    binfile=open(outpath+"/output "+outcount+" "+numcount+".mid",'wb')
    MyMIDI.writeFile(binfile)
    print(counter,"\n",track,channel,pitch,time,duration,volume)
    binfile.close()
    return O
Example #2
0
def play(request):
  global outputId

  json = simplejson.loads(request.POST.get('notes'))

  midiFile = MIDIFile(1)

  track = 0
  time = 0
  midiFile.addTrackName(track, time, "Sample Track")
  midiFile.addTempo(track, time, 120)

  channel = 0
  volume = 100

  string = ""

  for note in json['notes']:
    pitch = strToMidiPitch(note['pitch'])
    duration = note['duration']
    start = note['start']
    midiFile.addNote(track, channel, pitch, start, duration, volume)
    string += "added note " + note['pitch'] + ": " + str(pitch) + ", "

  binfile = open("/tmp/output.mid", 'wb')
  midiFile.writeFile(binfile)
  binfile.close()

  call(['fluidsynth', '-l', '-F', '/tmp/output_'+str(outputId)+'.wav', '/usr/share/sounds/sf2/FluidR3_GM.sf2', '/tmp/output.mid'])
  call(['lame', '--preset', 'standard',
        '/tmp/output_'+str(outputId)+'.wav',
        '/tmp/output_'+str(outputId)+'.mp3'])
  outputId += 1

  return HttpResponse(outputId-1)
def MidiFileCreator(melody,song):  
    bpm = melody['bpm']
    pitches = melody['pitches']
    parts = [t.split('.') for t in melody['times']]
    times = [4*int(l)+int(r)-1 for l,r in parts]
    durations = melody['durations']
    chord_pitches = song['chord_pitches']
    chord_times = song['chord_times']
    chord_center = song['chord_center']
    ListOfRelativeChordVoicings = song['chord_pitches']
    token = melody['token']
    MyMIDI = MIDIFile(1)
    track = 0
    channel = 0
    time = 0
    duration = 4
    volume = 100
    MyMIDI.addTrackName(track,time,"Herp derp")
    MyMIDI.addTempo(track,time,bpm)
    #Sends Chords to MIDI
    root = int(chord_center)
    for chord in ListOfRelativeChordVoicings:
        for note in chord:
            Intnote = int(note + root)
            MyMIDI.addNote(track,channel,Intnote,time,duration,volume)
        time = time + 4   
    for note,time in zip(pitches,times):
        MyMIDI.addNote(track,channel,int(note),int(time),1,volume)
    binfile = open(base + "static/songs/" + token + ".mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
    return "blah"
Example #4
0
def make_song_file(mood, key, syllables):
    # create the MIDIFile object with 1 track
    MyMIDI = MIDIFile(1)
    if mood == "mood1":
        mood = pass1
    elif mood == "mood2":
        mood = happy1
    elif mood == "mood3":
        mood = cool1

    # tracks are numbered from zero. times are measured in beats.

    track = 0
    time = 0

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

    key = key % 12
    MyMIDI = add_chords(MyMIDI, mood, key)
    MyMIDI = add_notes(MyMIDI, syllables, key, mood)

    # and write it to disk.
    binfile = open("song.mid", "wb")
    MyMIDI.writeFile(binfile)
    binfile.close()
Example #5
0
def midFile(melody):
    MyMIDI = MIDIFile(1)

    track = 0
    time = 0

    MyMIDI.addTrackName(track, time, "Vireo")
    MyMIDI.addTempo(track, time, 340)

    track = 0
    channel = 0
    time = 0
    volume = 100

    for i in melody:
        data = i.split()
        MyMIDI.addNote(track, channel, int(data[0].strip()), time, int(data[1].strip()), volume)
        time = time + int(data[1].strip())

    midi = ""
    binfile = open("./static/test.mid", "wb")
    MyMIDI.writeFile(binfile)
    binfile.close()
    binfile = open("./static/test.mid", "rb")
    midi = binfile.read()
    binfile.close()

    return midi
Example #6
0
def convert_to_song(file_name):
	
	mf = MIDIFile(1)
	track = 0

	time = 0
	mf.addTempo(track, time, 240)

	channel = 0
	volume = 100
	
	file_loc = os.path.join(os.getcwd(), file_name+'.csv')
	with open(file_loc, "rb") as csvfile:
		reader = csv.reader(csvfile)
		reader = list(reader)
		"""
		row_count = sum(1 for row in reader)
		for i in range(1, row_count):
			print reader[i]
		"""
		i = 1
		while i < len(reader):
		#for i in range(1, len(reader)):
			close = reader[i][4]
			pitch = get_pitch(float(close))
			time += 1
			duration = 1
			mf.addNote(track, channel, pitch, time, duration, volume)
			i += 20
			#print i

	with open('static/' + file_name + '.mid', 'wb') as outf:
		mf.writeFile(outf)
	outf.close()
Example #7
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)
    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"
Example #9
0
def test_one_text_column():
    '''
    A data frame with a single integer column
    should be converted correctly.
    '''
    expected = MIDIFile(1)
    expected.addTrackName(0,0,"vocals")
    expected.addTempo(0,0,120)
    for time,note in enumerate([38, 40, 42, 43]):
        expected.addNote(0,0,note,time,1,100)

    df = pandas.DataFrame([
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'mushroom'},
        {'vocals':'mushroom'},
    ])
    observed = df_to_midi(df, bpm = 120)

    n.assert_equal(observed, expected)
def saveMIDI(filename, noteOnsets, melody, tempo, Fs, hopSize):
    barOnsets = (noteOnsets*hopSize/float(Fs))*(tempo/60)    #Onsets dado en barra
    notes = quantizeNote(melody)    
    track = 0
    time = 0       
    MIDI = MIDIFile(1)
    
    # Add track name and tempo.
    MIDI.addTrackName(track,time,"MIDI TRACK")
    MIDI.addTempo(track,time,tempo)
    
    channel = 0
    volume = 100
    
    for i in range(np.size(barOnsets)):
        pitch = notes[noteOnsets[i]+1]  #leer el pitch en el siguiente frame al onset
        if pitch > 0:
            time = barOnsets[i]
            if i == np.size(barOnsets)-1:
                duration = 1
            else:
                duration = barOnsets[i+1]-barOnsets[i] 
            
            MIDI.addNote(track,channel,pitch,time,duration,volume)

    # And write it to disk.
    binfile = open(filename, 'wb')
    MIDI.writeFile(binfile)
    binfile.close()    
Example #11
0
def matrix_to_midi(notes, filename = 'matrix.mid', tempo = 60):
    """ Simplify midi generation
        note format: PITCH|START|DURATION|VOLUME """
    # Midi file with one track
    mf = MIDIFile(1)

    track = 0
    time = 0
    mf.addTrackName(track, time, filename[7:-4])

    # Default
    # FIXME tempo -- time relation is not well defined
    mf.addTempo(track, time, tempo)
    channel = 0

    time_per_tick = 2**-5

    for note in notes:
        pitch = note[0]
        start = note[1] * time_per_tick
        stop  = note[2] * time_per_tick
        vol   = note[3]
        mf.addNote(track, channel, pitch, start, stop, vol)

    # Save as file
    with open(filename, 'wb') as fout:
        mf.writeFile(fout)
Example #12
0
class Generator:
    def __init__(self, tempo = 120):
        self.midi_file = MIDIFile(1)
        self.midi_file.addTrackName(0, 0, "track")
        self.midi_file.addTempo(0, 0, tempo)

        self.current_time = 1

    def add_pause(self, length = 1):
        self.current_time = self.current_time + length

    def add_chord(self, base, notes, length = 1):
        for note in notes:
            self.midi_file.addNote(0, 0, base + note, self.current_time, length, VOLUME_TABLE[len(notes)])
        self.add_pause(length)

    def add_pattern(self, base, pattern):
        for item in pattern:
            length = item[len(item) - 1]
            self.add_chord(base, item[0 : len(item) - 1], length)

    def write(self, filename):
        output_file = open(filename, 'wb')
        self.midi_file.writeFile(output_file)
        output_file.close()
Example #13
0
def main(argv):

 if len(argv) == 1:
  for line in open(argv[0],'r'):
   MyMIDI = MIDIFile(1)
   MyMIDI.addTempo(0,0,120)
   array = line.split(";")
   MyMIDI = makeProgression(noteToPitch(array[0]),noteToPitch(array[1]),array[2].split(" "), MyMIDI)
   writeToFile(array[3].rstrip('\n'), MyMIDI)
   MyMIDI = None
 else:
  print "Enter first note in sequence: "
  firstnote = noteToPitch(raw_input())
  # process first note

  print "Enter last note in sequence: "
  lastnote = noteToPitch(raw_input())
  # process last note

  print "Enter first note progression in the following format: "
  print "note/duration note/duration note/duration"
  progression = raw_input()
  # process note progression

  progression = progression.split(" ")
  makeProgression(firstnote,lastnote,progression)

  print "Enter file name: "
  filename = raw_input()
  writeToFile(filename)
Example #14
0
    def write_midi_file(self, file_object):
        """Writes midi generated from this tab to the given file object."""
        # Throw an exception if there are note names for which we can't
        # determine the proper note numbers.
        unmappable_note_names = self.note_types.difference(
            self.note_name_to_number_map.keys())
        if unmappable_note_names:
            raise UnmappableNoteNamesException(unmappable_note_names)

        midifile = MIDIFile(1)
        track = 0
        channel = 9
        duration = round(4.0 / self.divisions_in_bar, 10)
        # 4.0 is because midiutil's  unit of time is the quarter note.
        midifile.addTrackName(track, 0, "")
        midifile.addTempo(track, 0, self._bpm)
        for note in self.walk_notes():
            strike_type = note['strike_type']
            volume = self._volume_for_strke_type(strike_type)
            if strike_type == 'r':
                pitch = GM_SPEC_NOTE_NAME_TO_NUMBER_MAP['Sticks']
            else:
                pitch = self.note_name_to_number_map[note['note_type']]
            midifile.addNote(track, channel, pitch, note['time'], duration,
                             volume)
        midifile.writeFile(file_object)
Example #15
0
    def render(self, doc, output_file='output.mid'):
        ''' Produces actual output.
        Assumptions: separate channel for each DataObject'''
        # Note - I fixed a bug in MidiFile.py that was causing crashes (part of the midiutil lib).
        # Author confirms this is a bug, and will eventually fix and patch, but for now there's a
        # modified version of midiutil bundled with the project.

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

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

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

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

        # And write it to disk.
        with open(output_file, 'wb') as binfile:
            MyMIDI.writeFile(binfile)
        return MyMIDI
Example #16
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)
Example #17
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()
Example #18
0
    def run(self):
        inputObj = self.get_input("input") #obiekt interfejsu wejściowego
        outputGraph = self.get_output("outputGraph") #obiekt interfejsu wyjściowego
        outputPitch = self.get_output("outputPitch") #obiekt interfejsu wyjściowego
        prev_note = 0

        #init midi
        track = 0
        time = 0
        MyMIDI = MIDIFile(1)
        MyMIDI.addTrackName(track,time,"Sample Track")
        MyMIDI.addTempo(track,time,120)

        try:
            while self.running():
                data_input = inputObj.read()

                N = data_input["N"]
                audioData = base64.b64decode(data_input["data"])
                MAX_y = data_input["MAX_y"]

                y = np.array(struct.unpack("%dh" % (N * CHANNELS), audioData)) / MAX_y
                y_L = y[::2]
                y_R = y[1::2]

                Y_L = np.fft.fft(y_L, nFFT)
                Y_R = np.fft.fft(y_R, nFFT)

                # Łączenie kanałów FFT, DC - prawy kanał
                Y = abs(np.hstack((Y_L[-nFFT/2:-1], Y_R[:nFFT/2])))

                samples = np.fromstring(audioData, dtype=np.int16)

                #wyliczenie dzwieku
                rawnote = analyse.musical_detect_pitch(samples)

                if rawnote is not None:
                    note = np.rint(rawnote)

                    #wyślij nutę na wyjście
                    outputPitch.send(note)

                    if note != prev_note:

                        #MyMIDI.addNote(track,channel,pitch,time,duration,volume)
                        MyMIDI.addNote(0,0,note,time,1,100)
                        time+=1
                        prev_note = note

                output = {"db_table": list(Y)}
                outputGraph.send(output)

        #save midi on exit
        except:
            binfile = open("output.mid", 'wb')
            MyMIDI.writeFile(binfile)
            binfile.close()
Example #19
0
def initializeTrack(tempo=100, numTracks=15):
  """Create a song with the given tempo."""
  song = MIDIFile(numTracks)

  time = 0
  for track in range(numTracks):
    song.addTrackName(track, time, "Track " + str(track))
    song.addTempo(track, time, tempo)

  return song
def write(predicted, min_pitch):
    from midiutil.MidiFile import MIDIFile
    m = MIDIFile(1)
    m.addTempo(0, 0, 70)
    for t, pitches in enumerate(predicted.T):
        for i, on in enumerate(pitches):
            note = i + min_pitch
            if on:
                m.addNote(0, 0, note, t / 8.0, 1 / 8.0, 100)
    with open('out.mid', 'wb') as f:
        m.writeFile(f)
Example #21
0
def create_midi(tempo, data):
  print 'Converting to MIDI.'
  song = MIDIFile(1)
  song.addTempo(0, 0, tempo)

  grouped = [(note, sum(1 for i in g)) for note, g in groupby(data)]
  time = 0
  for note, duration in grouped:
    add_note(song, 0, note, time, duration)
    time += duration
  return song
Example #22
0
 def reset_track(self):
     if self.track:
         del self.track
         self.track = None
     track = MIDIFile(1)
     track.addTrackName(0, 0, "beatfruit-recording") # FIXME: Use a nicer name, template it and include timestamp???
     track.addTempo(0, 0, 120) # FIXME: Will impliment tempo changes later!
     self.track = track
     self.events = []
     self.chans = {}
     self.last_timestamp = None
     self.base_time = None
def playingmusic(O):
    from midiutil.MidiFile import MIDIFile
    MyMIDI=MIDIFile(1, removeDuplicates=False, deinterleave=False)
    track=0
    time=0
    MyMIDI.addTrackName(track,time,"Sample")
    MyMIDI.addTempo(track,time,120)
    for x in range(0,3000):
        counter=x
        for midout in range(0,3):
            O,MyMIDI,vol,pitch,time=playMIDI(x,counter, midout, O, MyMIDI)
            print(counter, midout, pitch, vol, time)
    return O,MyMIDI
Example #24
0
def convertToMIDI(piece):
    mfile = MIDIFile(1)
    track = 0
    time = 0
    tempo = 160

    mfile.addTrackName(track, time, "test")
    mfile.addTempo(track, time, tempo)

    channel = 0
    volume = 100

    # Actual magic happens here
    i = 0
    while i < len(piece)-1:
        # Get the corresponding pitch for the note
        pitch = mapping[piece[i][0]]
        diff = int(piece[i][-1]) - 4
        pitch += diff * 12

        # If we're dealing with a continued note
        if piece[i] == piece[i+1]:
            n = i
            duration = 0
            
            # Keep increasing the duration by 2 for
            # every consecutive matching note
            while piece[n] == piece[n+1]:
                #print n
                duration += 2
                if n+1 == len(piece):
                    break
                # Single note duration is 2
                n += 1
            mfile.addNote(track, channel, pitch, i*2, duration, volume)
            i = n

        # If we're dealing with a single note, add it
        else:
            mfile.addNote(track, channel, pitch, i*2, 2, volume)

            # If we're on the penultimate note,
            # add the last note too
            if i == len(piece) - 1:
                pitch = mapping[piece[i+1]]
                mfile.addNote(track, channel, pitch, i*2, 2, volume)
        i += 1

    bfile = open("output.mid", "wb")
    mfile.writeFile(bfile)
    bfile.close()
Example #25
0
def create_midi(frequency):
    my_midi = MIDIFile(1)
    track = 0
    channel = 0
    pitch = 69 + 12 * log(max(frequency) / 440, 2)

    time = 0
    duration = 1
    volume = 100

    my_midi.addTempo(track, time, 120)
    my_midi.addNote(track, channel, pitch, time, duration, volume)

    return my_midi
Example #26
0
def WriteMidi(notes, tempo, file):
    MyMIDI = MIDIFile(1)

    MyMIDI.addTrackName(0,0,"Sample Track")
    MyMIDI.addTempo(0,0,tempo)

    time= 0
    for (name, d, length) in notes:
        MyMIDI.addNote(0,0,60,time,length*4,100)
        time+= length*4

    binfile = open(file, 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
Example #27
0
def main(argv=None):

	if argv is None:
		argv = sys.argv

	txtFileName = argv[1]
	txtFile = open(txtFileName, 'r')
	charsForNotes = txtFile.read()
	txtFile.close()

	#Setup default values
	rootNote = 0;
	track = 0
	time = 0
	tempo = 120
	channel = 0
	duration = 1
	volume = 100


	midiFile = MIDIFile(12)
	midiFile.addTrackName(0, time, "1")
	midiFile.addTrackName(1, time, "2")
	midiFile.addTrackName(2, time, "3")
	midiFile.addTrackName(3, time, "4")
	midiFile.addTrackName(4, time, "5")

	midiFile.addTempo(track, time, tempo)

	
	i = 0
	while(i < len(charsForNotes)):
		j = 0
		#double every 4th beat
		durationMult = (i%4 == 0) + 1
		while(j < 5):
			pitch = pickPitch(charsForNotes[i], rootNote+(12*j))
			if charsForNotes[i] is ' ':
				midiFile.addNote(j, channel, pitch, time, duration*durationMult, 0)
			else:
				midiFile.addNote(j, channel, pitch, time, duration*durationMult, volume)
			j += 1
		time += 1
		i += 1

	
	mFile = open("mozart.mid", 'wb')
	midiFile.writeFile(mFile)
	mFile.close()
Example #28
0
def write_midi(filename, sequence):
    filename = "music/"+filename
    midi = MIDIFile(1)
    track = 0
    start_time = 0
    midi.addTrackName(track, start_time, filename[:-4])
    tempo = random.randrange(120, 480)
    midi.addTempo(track, start_time, tempo)
    for seq in range(len(sequence)):
        for note in sequence[seq]:
            midi.addNote(track, 9, note.pitch, note.time, note.duration, note.volume)
        # midi.addProgramChange(0, seq, 0, instrList[seq])
    f = open(filename, 'w')
    midi.writeFile(f)
    f.close()
Example #29
0
def createWav(word_lengths):
	note_lengths = map(wordlen_to_notelen, word_lengths)
	print note_lengths
	note_library = notes('c', 'major')
	print note_library
	MyMIDI = MIDIFile(1)
	MyMIDI.addTempo(0,0,120)
	total = 0.0
	for d in note_lengths:
		MyMIDI.addNote(0,0,int(note_library[random.randint(0,7)]),total,d,100)
		total += d
	
	binfile = open("output.mid", 'wb')
	MyMIDI.writeFile(binfile)
	binfile.close()
Example #30
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()
def save_midi(outfile, notes, tempo):

    track = 0
    time = 0
    midifile = MIDIFile(1)

    # Add track name and tempo.
    midifile.addTrackName(track, time, "")
    midifile.addTempo(track, time, tempo)

    channel = 0
    volume = 100

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

    # And write it to disk.
    binfile = open(outfile, 'wb')
    midifile.writeFile(binfile)
    binfile.close()
Example #32
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)
Example #33
0
    for note in note_group:
        if (note.note != None):
            print([note.note + " " + note.sym])
        else:
            print([note.sym])

    midi = MIDIFile(1)

    track = 0
    time = 0
    channel = 0
    volume = 100

    midi.addTrackName(track, time, "Track")
    midi.addTempo(track, time, 130)

    duration = None
    for note in note_group:
        note_type = note.sym
        if (len(note_type) != 2):
            if note_type == "1":
                duration = 4
            elif note_type == "2":
                duration = 2
            elif note_type == "4,8":
                duration = 1 if len(note_group) == 1 else 0.5
            pitch = note.pitch
            midi.addNote(track, channel, pitch, time, duration, volume)
            time += duration
plt.show()

pitch_human = scale_pitch_human(
    humanpop)  #calls the scaling function to create a list of scaled pitches
pitch_elnino = scale_pitch_elnino(elnino)
#time1 = scale_time(data6) #calls the scaling time function to create a list of scaled times

# create your MIDI object
mf = MIDIFile(2)  # only 1 track
track1 = 0  # the only track
track2 = 1
time1 = 0  # start at the beginning
time2 = 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)
def write_midi_roll_to_midi(x, out_path):
    """Write out midi_roll to midi file. 
    
    Args: 
      x: (n_time, n_pitch), midi roll. 
      out_path: string, path to write out the midi. 
    """
    step_sec = cfg.step_sec

    def _get_bgn_fin_pairs(ary):
        pairs = []
        bgn_fr, fin_fr = -1, -1
        for i2 in range(1, len(ary)):
            if ary[i2 - 1] == 0 and ary[i2] == 0:
                pass
            elif ary[i2 - 1] == 0 and ary[i2] == 1:
                bgn_fr = i2
            elif ary[i2 - 1] == 1 and ary[i2] == 0:
                fin_fr = i2
                if fin_fr > bgn_fr:
                    pairs.append((bgn_fr, fin_fr))
            elif ary[i2 - 1] == 1 and ary[i2] == 1:
                pass
            else:
                raise Exception("Input must be binary matrix!")

        return pairs

    # Get (pitch, bgn_frame, fin_frame) triple.
    triples = []
    (n_time, n_pitch) = x.shape
    for i1 in range(n_pitch):
        ary = x[:, i1]
        pairs_per_pitch = _get_bgn_fin_pairs(ary)
        if pairs_per_pitch:
            triples_per_pitch = [(i1, ) + pair for pair in pairs_per_pitch]
            triples += triples_per_pitch

    # Sort by begin frame.
    triples = sorted(triples, key=lambda x: x[1])

    # Write out midi.
    MyMIDI = MIDIFile(1)  # Create the MIDIFile Object with 1 track
    track = 0
    time = 0
    tempo = 120
    beat_per_sec = 60. / float(tempo)
    MyMIDI.addTrackName(track, time, "Sample Track")  # Add track name
    MyMIDI.addTempo(track, time, tempo)  # Add track tempo

    for triple in triples:
        (midi_pitch, bgn_fr, fin_fr) = triple
        bgn_beat = bgn_fr * step_sec / float(beat_per_sec)
        fin_beat = fin_fr * step_sec / float(beat_per_sec)
        dur_beat = fin_beat - bgn_beat
        MyMIDI.addNote(
            track=0,  # The track to which the note is added.
            channel=0,  # the MIDI channel to assign to the note. [Integer, 0-15]
            pitch=midi_pitch,  # the MIDI pitch number [Integer, 0-127].
            time=
            bgn_beat,  # the time (in beats) at which the note sounds [Float].
            duration=dur_beat,  # the duration of the note (in beats) [Float].
            volume=100)  # the volume (velocity) of the note. [Integer, 0-127].
    out_file = open(out_path, 'wb')
    MyMIDI.writeFile(out_file)
    out_file.close()
Example #36
0
#AO INVES DISSO POSSO USAR O SCIPY.FLATTEN:
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html
#seq2D.flatten('C') #=por linha = ([[1,2], [3,4]]) = ([1, 2, 3, 4])
#seq2D.flatten('F') #=por coluna = ([[1,2], [3,4]]) = ([1, 3, 2, 4])

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

# Tracks are numbered from zero. Times are measured in beats.

track = 0
time = 0
# Add track name and tempo.
MyMIDI.addTrackName(track, time, "Sample Track")
if (int(args["tempo"]) > 60):
    MyMIDI.addTempo(track, time, int(args["tempo"]))
else:
    MyMIDI.addTempo(track, time, 120)
# Add a note. addNote expects the following information:
track = 0
channel = 0
#pitch = 60
time = 0
repeticoes = 0
volume = 100
print seq

#vai dizer por quantos segundos as notas que se repetem vao ficar "pressionadas"
#height*width is o tamanho maximo, mas se houve repeticoes, ele vai ser menor do que isso for sure
#duration_timing=array.array('i',(0,)*(height*width))
duration_timing = []
Example #37
0
def generate_music(img,
                   note_info,
                   algorithm,
                   musicfile,
                   octave_span=3,
                   tot_time=60):
    '''
        img: Center of image should be center of circle. Cropped closely to size
        algorithm = 'concentric' or 'radial'
        note_info: 4xn numpy array with format [noteValue, radialDistance, angleFrom+YAxis, diameterOfColony]. n = number of notes
        musicfile: string specifying output filename
        octave_span: odd number of octaves to span notes across
        total_time = seconds
        possible future use: sorted_index = np.argsort()
    '''
    if (octave_span % 2 == 0) and (octave_span != 0):
        print "ERROR: 'octave_span' must be odd"
        return None
    if (octave_span > 9):
        print "ERROR: 'octave_span' beyond limits of MIDI"  # technically exist octaves from 0-9.5
        return None
    if (type(octave_span) != int):
        print "Casting 'octave_span' %s to an integer %d" % (str(octave_span),
                                                             int(octave_span))
        octave_span = int(octave_span)
    print musicfile

    # create your MIDI object
    mf = MIDIFile(
        5, adjust_origin=True)  # only 1 track, changed adjust_origin to T
    track = 0  # the only track
    time = 0  # start at the beginning

    if (algorithm == 'concentric'):  # where max = total_time
        sort_by = note_info[1, :]  # radial distance
        max_time = (img.shape[0] + img.shape[1]) / 4.0  # max, radius (average)
    elif (algorithm == 'radial'
          ):  # normalization, where mean = 0; max - min = octave_span
        sort_by = note_info[2, :]  # angle
        max_time = 2.0 * pi  # aka 360 degrees
    else:
        print "ERROR: Invalid 'algorithm' mode"
        return None

    if (octave_span != 0):
        octave_factor = (np.amax(note_info[3, :]) -
                         np.amin(note_info[3, :])) / octave_span
    time_factor = tot_time / max_time
    mf.addTrackName(track, time, "Biota Beats Sample")
    mf.addTempo(track, time, 60)  # tempo/bpm (param3) to be parametrized

    #print "sort_by", sort_by

    channel = 0
    note_conversion = {
        0: 60,
        1: 62,
        2: 64,
        3: 67,
        4: 69
    }  # hard-coded for pentatonic scale, may change

    # Generate notes
    print "Note\tPitch\trelOct\tStart(Beats)\tTrack"
    for i in range(note_info.shape[1]):
        if (octave_span != 0):
            octave = int(
                floor((note_info[3, i] - np.amin(note_info[3, :])) /
                      octave_factor)) - (octave_span / 2)
        else:
            octave = 0
        pitch = note_conversion[note_info[0, i]] + (
            12 * octave)  # 12 half-notes per octave
        time = sort_by[i] * time_factor
        '''BUG TODO: parameterize tempo to use total time.
        e.g. if we use 'angle' algorithm mode,
        and sort_by[i] = 2*pi radians, time_factor = 60/(2*pi)
        then final note is ALWAYS played at 60th beat'''
        duration = 5  # to be parameterized
        volume = 100  # to  be parameterized
        track = int(note_info[0, i])
        print i, "\t", pitch, "\t", octave, "\t", time, "\t", track
        mf.addNote(track, channel, pitch, time, duration, volume)

    # write it to disk
    with open(musicfile, 'wb') as outf:
        mf.writeFile(outf)
Example #38
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)
Example #39
0
def create_arpeggios_chord_variation(emotion_text_file, file_name):
    """
	Given the emotion values from a video, creates a midi file where the notes are dependent on 
	the emotion values. The higher the arousal value, the faster the arpeggio is played. The higher
	the valence value, the more major the chord played.

	:param emotion_text_file: path to text file holding emotion values for video
	:param file_name: name for midi file_name
	:type emotion_text_file: str
	:type file_name: str
	:returns: None
	:rtype: None 
	"""
    MyMIDI = MIDIFile(1)

    track = 0
    time = 0

    # creates a template for a midi track
    MyMIDI.addTrackName(track, time, file_name)
    MyMIDI.addTempo(track, time, 120)  # 120 bpm

    channel = 0
    volume = 120
    base_note = 60

    # reads arousal and valence values from emotions text file and adds them to an arousal
    # list and a valence list respectively
    arousal_list = []
    valence_list = []
    with open(emotion_text_file, 'r') as emotions_text:
        for emotion in emotions_text:
            emotion = emotion[:-1].split(",")
            arousal_list.append(float(emotion[0]))
            valence_list.append(float(emotion[1]))

    # finds range of valence values specific to the video
    min_v = min(valence_list)
    max_v = max(valence_list)

    # creates 12 boundaries ("thresholds") of values within range
    steps = (max_v - min_v) / 4
    thresholds = np.arange(min_v, max_v + steps, steps)

    duration = arousal_list[0]

    # for arousal, valence in emotions list:
    for arousal, valence in zip(arousal_list, valence_list):
        # arousal to duration relationship is logarithmic - difference when arousal is low
        # is more evident, so arousal values are slightly shifted as to never be 1 or 0
        arousal = arousal * 0.85 + 0.01
        arousal = abs(math.log(arousal))

        # determine chord/notes of arpeggio that will be played, depending on valence value
        if thresholds[0] <= valence < thresholds[1]:
            i = 3
        elif thresholds[1] <= valence < thresholds[2]:
            i = 2
        elif thresholds[2] <= valence < thresholds[3]:
            i = 5
        else:
            i = 4

        # add notes until total duration reaches 6
        total_length = 0
        under_limit = True
        while under_limit:
            duration = arousal
            for pitch in [
                    base_note, base_note + i, base_note + 7, base_note + i
            ]:
                MyMIDI.addNote(track, channel, pitch, time, duration,
                               volume)  # add note to midi track
                total_length += duration
                time += duration
                if total_length > 6:
                    under_limit = False
                    break

    # write midi file
    file_name = file_name + '.mid'
    binfile = open(file_name, 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
    return
Example #40
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)
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])
Example #42
0
def start_midifile(track, time, fname_no_ext, channel, volume, bpm):
    mf = MIDIFile(1)
    mf.addTrackName(track, time, fname_no_ext)
    mf.addTempo(track, time, bpm)
    mf.addKeySignature(track, time, 0, SHARPS, MAJOR)
    return mf
Example #43
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()
Example #44
0
                # Add the call branch 
                branches_dict[current_branch].append(('sound_call', parts[1]))
        elif parts[0] == "note_type":
            speed = int(parts[1][0:len(parts[1]) - 1])
            branches_dict[current_branch].append(('note_type', speed))

            # TODO: Volume and fade
        elif parts[0] == "sound_loop":
            count = int(parts[1][0:len(parts[1]) - 1])
            loop_branch = parts[2]
            add_branch_loops(current_branch, count, loop_branch)

# Edge case to deal with the last channel duration length just in case it is the max 
max_ch_dur_length = max(current_ch_dur_length, max_ch_dur_length) * loop_times

MyMIDI.addTempo(track, time, tempo) 

# Add the notes to the midi file
for cd in channel_details:
    sound_call_branches = []

#cd = channel_details[2]
#sound_call_branches = []

    total_notes = 0
    total_duration = 0

    # First establish all the branches that are called by sound_call
    for branch in cd.branches:
        for tup in branches_dict[branch]:
            opcode = tup[0]
Example #45
0
class Midi:
    """Classe Midi"""
    #Atributos Privados '__'
    midinote = 0

    #Contrutor do MIDI
    def __init__(self, name, track, time, channel, volume,
                 duration):  #Construtor
        self.name = name
        self.duration = duration
        self.volume = volume
        self.channel = channel
        self.time = time
        self.track = track

    #Define um novo arquivo com o formato MIDI
    def setNovo(self):
        self.midi = MIDIFile(1)  # create my MIDI file
        self.midiTime = 0

    #Mais alguns construtores, setter's e getter's
    def setName(self, name):
        self.name = name

    def setDuration(self, duration):
        self.duration = duration

    def setVolume(self, volume):
        self.volume = volume

    def setChannel(self, channel):
        self.channel = channel

    def setTime(self, time):
        self.time = time

    def setTrack(self, track):
        self.track = track

    def getTrack(self):
        return self.track

    def getName(self):
        return self.Name

    def getVolume(self):
        return self.__volume

    def getChannel(self):
        return self.channel

    def getTime(self):
        return self.time

    def getDuration(self):
        return self.duration

    def addNoteToMidi(self, nota):
        '''Adicionando cada nota .mid ao .mid que vai conter todas as notas'''
        self.midi.addTempo(self.track, self.midiTime, 120)  #120 bpm
        # Cria .mid com a nota vinda do parametro
        self.midi.addNote(self.track, self.channel, int(nota), self.midiTime,
                          self.duration, 127)  #Coloca Nota musical no arquivo
        self.midiTime = self.midiTime + 2

    #Setter do MIDI
    def setMIDI(self):
        with open('outmid2.mid', 'wb') as outf:
            self.midi.writeFile(outf)

    #Define o novo MIDI a ser salvo com as devidas configurações
    def criaNovoMIDI(self, notas):
        mf = MIDIFile(1)  # create my MIDI file
        mf.addTrackName(self.track, self.time, self.name)
        mf.addTempo(self.track, self.time, 120)  #120 bpm
        self.midinote = notas
        # Cria .mid com a nota vinda do parametro
        mf.addNote(self.track, self.channel, int(notas), self.time,
                   self.duration, 127)  #Coloca Nota musical no arquivo
        # Para Criar o BIG MIDI
        self.addNoteToMidi(int(notas))

        with open(self.name, 'wb') as outf:
            mf.writeFile(outf)

        # cria .wav com o nome do parametro (vindo do terminal)
        spec = importlib.util.spec_from_file_location(
            "__main__", "../PySynth/readmidi.py")
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
Example #46
0
from midiutil.MidiFile import MIDIFile
import random
import time as tiemp
from decimal import Decimal
from array import *

mf = MIDIFile(1)
track = 0
time = 0
mf.addTrackName(track, time, "Music mash")
mf.addTempo(track, time, 80)
channel = 0
volume = 100


def append(pt, t, d):
    pitch = pt  # tn
    time = t  # bt start
    duration = d  # length of beat
    mf.addNote(track, channel, pitch, time, duration, volume)


pp = 67
ch = 0
rd = 200
rd = int(rd)
array = array('i', [])
print(f"max render time:{rd*9}s, {(rd*9)/60}min")
for n in range(rd):
    delay = random.randint(5, 9)
    for s in range(1):
Example #47
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]
        seq_in = [int_to_char[value] for value in pattern]

        #print result
        yPlot.append(result)
        xPlot.append(i)
        #sys.stdout.write(result)
        pattern.append(index)
        pattern = pattern[1:len(pattern)]

    track = trackCount
    channel = 0
    duration = 6
    volume = 100
    tempo = 180

    MyMIDI.addTempo(track, 0, tempo)

    for i in range(0, len(xPlot) - 1):
        timeStep = xPlot[i]
        pitch = yPlot[i]

        MyMIDI.addNote(track, channel, pitch, timeStep, duration, volume)

    trackCount = trackCount + 1

    print(time() - t0), 's'

# Write the midi file
binfile = open("result.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()
# A sample program to create a single-track MIDI file, add a note,
# and write to disk.
############################################################################

#Import the library
from midiutil.MidiFile import MIDIFile

# Create the MIDIFile Object
MyMIDI = MIDIFile(1)

# Add track name and tempo. The first argument to addTrackName and
# addTempo is the time to write the event.
track = 0
time = 0
MyMIDI.addTrackName(track, time, "Sample Track")
MyMIDI.addTempo(track, time, 120)

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

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

# And write it to disk.
binfile = open("output.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()
Example #50
0
if len(sys.argv) > 2:

	inFile = minidom.parse(sys.argv[1])
	outFile = open(sys.argv[2], 'wb')

	midiData = MIDIFile(len(inFile.getElementsByTagName('track')))

	tempo = int(inFile.getElementsByTagName('head')[0].attributes['bpm'].value)
	trackCnt=0

	for t in inFile.getElementsByTagName('track'):
		if t.getElementsByTagName('midiport'):
			channel = int(t.getElementsByTagName('midiport')[0].attributes['outputchannel'].value)

			midiData.addTrackName(trackCnt, channel, str(t.attributes['name'].value))
			midiData.addTempo(trackCnt, channel, tempo)

			for p in t.getElementsByTagName('pattern'):
				startPos = float(p.attributes['pos'].value)

				for note in p.getElementsByTagName('note'):
					midiData.addNote(	
						track		  =	  trackCnt, 				  \
						channel 	= 	channel, 						\
						pitch 		=	  int(note.attributes['key'].value)+24, 			            \
						time		  =	  (startPos + float(note.attributes['pos'].value))/48.0, 	\
						duration	=	  float(note.attributes['len'].value)/48.0,		            \
						volume		=	  int(note.attributes['vol'].value))

			trackCnt += 1
def construct_midi(results, img_name):
    """
    This function constructs and saves the midi file.
    :param results: Individual element names and their classifications.
    :param img_name: Input image name.
    """

    construct_output(indent_level="block",
                     message="Creating the '.midi' file.".format(img_name))

    # Create  MIDI object
    midi_file = MIDIFile(1)  # Only 1 track.
    track = 0  # Track number.
    time = 0  # Start at the beginning.

    # Add  properties to the midi file.
    midi_file.addTrackName(track, time, img_name)
    midi_file.addTempo(track, time, 120)

    # Convert note names to their numerical values (i.e. C4 -> 60)
    results = match_notes_to_midi_values(results)

    time_signature = "4/4"  # Default time signature

    max_bar_length = 4  # Length of one bar.
    current_bar_length = 0  # Length of the current bar.
    channel = 0  # Channel number (only one channel used).
    volume = 100  # Volume will be set to 100.
    time = 0  # Start on beat 0.

    for result in results:  # Iterate through all the classified images.
        result_name = result[0]  # Get the image name.
        pitch = -1  # Set the default pitch to be negative (not allowed, error check).
        note_duration = -1  # Set the default note value to be negative (not allowed, error check).

        if "clef" in result_name:  # Check the clef type (not important for now).
            pass  # TODO
        # Check the time signature (not important right now).
        elif "time_signature_4-4" in result_name:
            time_signature = "4/4"
            max_bar_length = 4  # Change the maximum bar length accordingly.
        elif "time_signature_2-4" in result_name:
            time_signature = "2/4"
            max_bar_length = 2  # Change the maximum bar length accordingly.
        elif "time_signature_3-4" in result_name:
            time_signature = "3/4"
            max_bar_length = 3  # Change the maximum bar length accordingly.
        elif "UNKNOWN" in result_name:
            # Notes that were classified are marked as "UNKNOWN".
            is_note = False  # Check is it a note (not used right now).

            # Set the real duration of the current note.
            if result[2] == "1/16":
                note_duration = 1 / 4
            elif result[2] == "1/8":
                note_duration = 1 / 2
            elif result[2] == "1/4":
                note_duration = 1
            elif result[2] == "1/2":
                note_duration = 2
            elif result[2] == "1/1":
                note_duration = 4

            note_pitch = result[1]  # Get the note pitch.
            if note_duration != -1 and note_pitch in range(
                    47, 82):  # Check if the data is correct.
                current_bar_length = current_bar_length + note_duration  # Update current bar length.
                # Add the note to the midi file.
                midi_file.addNote(track, channel, note_pitch, time,
                                  note_duration, volume)
                time = time + note_duration  # Update the timer.

        # Check if there are enough notes in the bar.
        elif "barline" in result_name:
            if current_bar_length < max_bar_length:
                # If notes are missing, add a rest to the bar, so that the rest if correctly aligned.
                duration = max_bar_length - current_bar_length
                if duration > 0:  # Check if the current bar duration is greater then maximum bar duration.
                    time = time + duration  # If it isn't, add a rest to the bar.
            current_bar_length = 0  # If a barline is reached, reset the current bar length.

    # Construct the path the the location where the generated midi files will be saved.
    midi_path = os.path.abspath(
        os.path.join(str(Path(__file__).parent.parent.parent), 'results'))
    midi_path = os.path.join(midi_path, img_name[:-4] + ".mid")
    with open(midi_path, 'wb') as out_file:
        # Save the midi file.
        midi_file.writeFile(out_file)

    construct_output(
        indent_level="block",
        message="Creating the '.midi' file done.".format(img_name))
def generateMIDI(lijstKick, lijstSnare, lijstHihat, beatsPerMeasure, MIDIname, tempo):

    if beatsPerMeasure == 14:
        divider = 2
    else:
        divider = 1

    track    = 0
    #used midi channel
    channel  = 9
    #set time, in beats
    time     = 0
    #set duration in beats, 0.5 -> .../8 time signature
    duration = 0.5
    #set bpm
    bpm    = tempo
    #set velocity
    velocity   = 100  # 0-127, as per the MIDI standard
    #create a track - defaults to format 2 - to enable addTimeSignature functionality

    if beatsPerMeasure > 7:
        n = 2#in the second mode(see main.py, the beatsPerMeasure is 14, but for the timeSignature we need 7)
    else:
        n = 1
    #numerator is the amount of counts in the timeSignature
    numerator = int(beatsPerMeasure / n)

    #checks if the beatsPerMeasure can be divided by 5
    if not(beatsPerMeasure % 5):
        d = 2#4th note----> 5/4
    else:
        d = 3#8th note ---> 7/8

    denominator = d

    MyMIDI = MIDIFile(2, adjust_origin=True)
    #set track, tempo and time
    MyMIDI.addTempo(track, time, bpm)
    #set timeSignature
    MyMIDI.addTimeSignature(track, time, numerator, denominator, clocks_per_tick=24, notes_per_quarter=8)

    counter = 0 #sets counter to zero

    for i in range(beatsPerMeasure):
    #wanneer de counter het aantal gegeven beats heeft doorlopen stopt de functie

        if counter == beatsPerMeasure:
            generateList = False
        else:
            if i in lijstKick:
                MyMIDI.addNote( track, channel, 36, (time + i / divider ) * duration, duration / divider, velocity)#In this line 'i' is time of event
                # counter += 1
            if i in lijstSnare:
                MyMIDI.addNote( track, channel, 38, (time + i / divider ) * duration, duration / divider, velocity)#In this line 'i' is time of event
                # counter += 1
            if i in lijstHihat:
                MyMIDI.addNote( track, channel, 42, (time + i / divider) * duration, duration / divider, velocity)#In this line 'i' is time of event
                counter += 1
            else:
                pass

    #create midi directory if it doesn't exist
    if not os.path.isdir(mypath):
       os.makedirs(mypath)
    # export a midi file
    with open(MIDIname, "wb") as output_file:
        MyMIDI.writeFile(output_file)

    print(colors.bcolors.GREEN + 'MIDI file is saved as: "'+ MIDIname + '"' + colors.bcolors.ENDC)
Example #53
0
        # Add final bar in staff
        staffs[i].addBar(bar)

    print("[INFO] Sequencing MIDI")
    midi = MIDIFile(
        1
    )  # create a MIDIFile Object named (midi), numTracks = 1: only has 1 track
    track = 0
    time = 0
    channel = 0
    volume = 100

    midi.addTrackName(
        track, time, "Track"
    )  # assinge the name track to the track, time (in beats) at which the track name event is placed
    midi.addTempo(track, time,
                  110)  # add a tempo to a track (in beats per min)

    ### Sequence MIDI

    for i in range(len(staffs)):
        print("==== Staff {} ====".format(i + 1))
        bars = staffs[i].getBars()
        for j in range(len(bars)):
            print("--- Bar {} ---".format(j + 1))
            primitives = bars[j].getPrimitives()
            for k in range(len(primitives)):
                duration = primitives[k].getDuration()
                if (primitives[k].getPrimitive() == "note"):

                    print(primitives[k].getPitch())
    bpm = numpy.median(bpms)
    print('Completed. Estimated Beats Per Minute:', bpm)

    if args.write_midi is not None:
        from midiutil.MidiFile import MIDIFile
        pitch = args.midi_note
        track = 0
        channel = 0
        duration = 0.125  # In beats
        volume = 127  # 0-127, as per the MIDI standard
        mf = MIDIFile(1)  # One track, defaults to format 1 (tempo track
        # automatically created)
        # Set time signature to 1/4
        # mf.addTimeSignature(track, 0, 1, 2, 24, notes_per_quarter=8)
        # Create new beats array that's evenly spaced and map to this
        beats_even = numpy.arange(0, beats.max() * 1.1, 0.5)
        bpm_mapped = numpy.interp(beats_even, beats, filtered)
        for tempo, beat in zip(bpm_mapped, beats_even):
            mf.addTempo(track, beat, tempo)
            mf.addNote(track, channel, pitch, beat, duration, volume)
        with open(args.write_midi, "wb") as output_file:
            mf.writeFile(output_file)

    if args.plot:
        plt.plot(beats, bpms)
        plt.plot(beats, filtered)
        plt.xlabel("Beat")
        plt.ylabel("BPM")
        plt.show()
Example #55
0
class MidiIO:
    def __init__(self, beat_per_minute, track_num=8):
        self.midi_player = MidiPlayer()
        self.mf = MIDIFile(track_num)
        start_time = 0
        for track in range(track_num):
            self.mf.addTrackName(track, start_time, "Track" + str(track))
            self.mf.addTempo(track, start_time, beat_per_minute)

        # by default use only 1 channel, and fix volume
        self.channel = 0
        self.volume = 127

    # track: 第几个音轨 from 0
    # pitch: 音调 Integer
    # start_beat: 开始的拍数 can be float
    # duration_beat: 持续的拍数 can be float
    def addNote(self,
                track,
                pitch,
                start_beat,
                duration_beat,
                volume=-1,
                channel=-1):
        if pitch <= 0:
            return
        if volume == -1:
            volume = self.volume
        if channel == -1:
            channel = self.channel
        self.mf.addNote(track, channel, pitch, start_beat, duration_beat,
                        volume)

    # only use the first line to speculate bpm
    def parse_ply(self, filename):
        auto_format_for_file(filename)
        data = read_io_file(filename)

        content_in_line = data.split("\n")
        if "pm=" not in content_in_line[0]:
            print(
                "please provide pm=beat_per_minute in the first line of ply file"
            )
            return
        else:
            attrs = content_in_line[0].split(",")
            for attr_unit in attrs:
                if "pm=" in attr_unit:
                    beat_per_min = int(attr_unit.replace("pm=", ""))
                    # print("got beat_per_min:", beat_per_min)

        track_num_required = 1
        for line in content_in_line[1:]:
            track_num = line.count("|") + 1
            if track_num > track_num_required:
                track_num_required = track_num
        # print("need track_num", track_num_required)

        self.mf = MIDIFile(track_num_required)
        start_time = 0
        for track in range(track_num):
            self.mf.addTrackName(track, start_time, "Track" + str(track))
            self.mf.addTempo(track, start_time, beat_per_min)

        track_start_beats = 0
        next_start = 0

        for (line,
             raw_line) in self.midi_player.parse_music_line(content_in_line):
            # print(line)
            # print(self.line_to_tracks(line))
            has_error = False
            for i, track in enumerate(self.line_to_tracks(line)):
                next_start, has_error = self.track_to_beats(
                    track, track_start_beats, i)
            if has_error:
                print("debug line:", raw_line)
                print(line)
            track_start_beats = next_start

    def convert_ply_to_midi(self, filename):
        self.parse_ply(filename)
        self.save_midi(filename + ".mid")

    def line_to_tracks(self, line):
        # print(line)
        beat_length = len(line)
        track_num = len(line[0])
        result = []
        for i in range(track_num):
            track = []
            for beat in range(beat_length):
                track.append(line[beat][i]["note"])
            result.append(track)
        return result

    def track_to_beats(self, track, track_start_beats=0, track_index=0):
        current_pitch = track[0][0]
        current_pitch_start = track_start_beats
        has_error = False
        if current_pitch < 0:
            print(
                "warining: midi io does not well support track start with -1, please combine it with formal track line"
            )
            has_error = True
        init = True
        current_beat_length = 1 / len(track[0])
        for i in range(len(track)):
            for j in range(len(track[i])):
                if init:
                    init = False
                    continue
                if track[i][j] == -1:
                    current_beat_length += 1 / len(track[i])
                else:
                    # add current_pitch (if not zero) with current_beat_length to the track with addNote
                    # print(track_index, current_pitch, current_pitch_start, current_beat_length)
                    self.addNote(track_index, current_pitch,
                                 current_pitch_start, current_beat_length)

                    # then
                    current_pitch = track[i][j]
                    current_pitch_start += current_beat_length
                    current_beat_length = 1 / len(track[i])
        # add current_pitch (if not zero) with current_beat_length to the track with addNote
        # print(track_index, current_pitch, current_pitch_start, current_beat_length)
        self.addNote(track_index, current_pitch, current_pitch_start,
                     current_beat_length)
        # for next track start
        return track_start_beats + len(track), has_error

    def save_midi(self, filename: str):
        if not filename.endswith(".mid"):
            filename += ".mid"
        # write it to disk
        with open(project_io_root + filename, 'wb') as outf:
            self.mf.writeFile(outf)
Example #56
0
import random
time_stamp = datetime.now().__str__()
time_stamp = time_stamp.split(".", 1)[0]
time_stamp = time_stamp.replace(" ", "_").replace(":", "_")

# Create the MIDIFile Object
MyMIDI = MIDIFile(1)
MyMIDI2 = MIDIFile(2)
# Add track name and tempo. The first argument to addTrackName and
# addTempo is the time to write the event.
track = 0
base_track = 1
start_time = float(0)
MyMIDI.addTrackName(track, start_time, "Melody Track")
MyMIDI2.addTrackName(base_track, start_time, "Base note Track")
MyMIDI.addTempo(track, start_time, 120)
MyMIDI2.addTempo(track, start_time, 120)
f = FibonacciNumber()
# Create seed base note with same duration
channel = 0
base_note = 60
duration = float(2)
volume = 100
# get a composer
code_set = ChordsSet()
c_gen = ChordsPatternGenerator(seed=time.ctime())
set_length = code_set.length
LENGTH = 40
PLAYGROUND = "In_Key_Chorus"

if __name__ == "__main__" and PLAYGROUND == "In_Key_Chorus":
Example #57
0
def createmidifile(scaledegrees, filepath):
    # Convert user input to midi file.
    savecheck = 0
    import os
    import os.path
    from pathlib import Path
    p = str(filepath)
    while savecheck == 0:
        defaultpath = os.getcwd()
        print('Current directory')
        print(defaultpath)
        usersave = input("Create MIDI File? (Y/N): ")
        usersave = usersave.upper()
        if usersave == "Y":
            if os.path.exists(filepath) == True:
                os.chdir(p)
                print("Inside Directory")
            if os.path.exists(filepath) == False:
                print('Creating Directory')
                os.makedirs(p)
                os.chdir(p)
            from midiutil.MidiFile import MIDIFile
            for i in range(len(scaledegrees)):
                scaledegrees[i] = int(scaledegrees[i] + 71)
            filename = ""
            while filename == "":
                filename = input("Enter your filename:  ")
                if (os.path.isfile(filename + ".mid")):
                    print("Error: File already exists!!")
                    filename = ""
                elif filename == "":
                    print("No characters detected.")
                    filename = ""
                else:
                    filename = filename + ".mid"
                    continue
            degrees = scaledegrees  # MIDI note number
            track = 0
            channel = 0
            time = 1  # In beats
            duration = 1  # In beats
            tempo = 85  # 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, pitch in enumerate(degrees):
                MyMIDI.addNote(track, channel, pitch, time + i, duration,
                               volume)
            print('Saving ' + filename + ' to ' + p + '...')
            with open(filename, "wb") as output_file:
                MyMIDI.writeFile(output_file)
            p = str(Path.cwd() / '')
            os.chdir(p)
            savecheck += 1
        elif usersave == 'N':
            p = str(Path.cwd() / '')
            os.chdir(p)
            savecheck += 1
        else:
            print('Invalid Input. Try Again')
            continue
Example #58
0
def main():
    # Open training file
    print("Reading notes from corpus files...")
    notesFilePath = "corpus/MichaelJacksonNotes.txt"
    notesFile = open(notesFilePath, 'r')
    notes = getTokensFromFile(notesFile)

    print("Creating unary transition matrix...")
    unaryTransitionMatrix = getUnaryTransitionMatrix(notes)

    print("Creating binary transition matrix...")
    binaryTransitionMatrix = getBinaryTransitionMatrix(notes)

    print("Creating ternary transition matrix...")
    ternaryTransitionMatrix = getTernaryTransitionMatrix(notes)

    print("Generating verse notes...")
    vn1 = 61
    vn2 = 61
    vn3 = 61
    verseList = generateVerse(
        unaryTransitionMatrix, binaryTransitionMatrix, ternaryTransitionMatrix, vn1, vn2, vn3)

    print("Generating chorus notes...")
    cn1 = 55
    cn2 = 57
    cn3 = 59
    chorusList = generateChorus(
        unaryTransitionMatrix, binaryTransitionMatrix, ternaryTransitionMatrix, cn1, cn2, cn3)

    print("Generating bridge notes...")
    bn1 = 69
    bn2 = 69
    bn3 = 68
    bridgeList = generateBridge(
        unaryTransitionMatrix, binaryTransitionMatrix, ternaryTransitionMatrix, bn1, bn2, bn3)

    print("Creating MIDI file...")
    songList = getSongList(verseList, chorusList, bridgeList)

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

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

    # Add track name and tempo.
    song.addTrackName(track, time, "Generated Song")
    song.addTempo(track, time, 240)

    for note in songList:
        track = 0
        channel = 0
        duration = random.randint(1, 4)
        noteIsSilent = note == -1
        if not noteIsSilent:
            pitch = note
            volume = 100
        else:
            pitch = 0
            volume = 0
        song.addNote(track, channel, pitch, time, duration, volume)
        time += 1

    # Write it to disk.
    binfile = open("output.mid", 'wb')
    song.writeFile(binfile)
    binfile.close()

    print("Program complete.")
Example #59
0
from midiutil.MidiFile import MIDIFile
import random
import time as tiemp
from decimal import Decimal
mf = MIDIFile(1)  
track = 0   
time = 0    
mf.addTrackName(track, time, "Music mash")
mf.addTempo(track, time, 120)
channel = 0
volume = 100

def append(pt,t,d):
    pitch = pt           # tn
    time = t             # bt start
    duration = d         # length of beat
    mf.addNote(track, channel, pitch, time, duration, volume)
pp = 67
ch = 0
rd = 200
rd = int(rd)
print(f"max render time:{rd*9}s, {(rd*9)/60}min")
for n in range(rd):
    delay = random.randint(5, 9)
    for s in range(1):
        pp = random.randint(pp-9, pp+9)
        if pp >= 90:
            pp = 68
        if pp <= 29:
            pp = 41
        append(pp, n+0.5, delay/2)    
Example #60
0
                       term.replace(' ', '-'))).read()).split()[0]

# Creates STD
std = numpy.std(pick[5])

# An upper limit to the energy - to compensate for sharp noises not necessarily from the melody
#limit = max(pick[5]) - numpy.mean(pick[5])

# Create your MIDI object
mf = MIDIFile(1)
track = 0
time = 0

# Creates the track with tempo from pickle
mf.addTrackName(track, time, "Sample Track")
mf.addTempo(track, time, pick[4])

# Add some notes
channel = 0
volume = 100

# Delay until the first note
mf.addNote(0, 0, 0, 0, float(pick[1][0]), 1)

# Add notes to the track respective of time, and magnitude for the volume
for x in range(0, len(pick[0])):
    try:
        if (float(pick[5][x]) > std):  # and (float(pick[5][x]) < limit):
            pitch = librosa.note_to_midi(pick[0][x][0])
            time = float(pick[1][x]) * (pick[4] / 60)
            duration = float(float(pick[1][x + 1]) - float(pick[1][x]))