예제 #1
0
    def savefile(self):
        """Construct MIDI file and save"""
        global pad_records, instrument, pitch

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

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

        filename = self.browse_filepath.get() + "/" + self.saveFileName.get()
        # try:
        binfile = open(filename, 'wb')
        MyMIDI.writeFile(binfile)
        binfile.close()
        print "saved"
예제 #2
0
class PatternWriterMIDI:
	def __init__(self, numtracks = 1):
		self.score = MIDIFile(numtracks)
		self.track = 0
		self.channel = 0
		self.volume = 64

	def addTrack(self, pattern, tracknumber = 0, trackname = "track", dur = 1.0):
		time = 0
		# naive approach: assume every duration is 1
		# TODO: accept dicts or PDicts
		try:
			for note in pattern:
				vdur = Pattern.value(dur)
				if note is not None and vdur is not None:
					self.score.addNote(tracknumber, self.channel, note, time, vdur, self.volume)
					time += vdur
				else:
					time += vdur
		except StopIteration:
			# a StopIteration exception means that an input pattern has been exhausted.
			# catch it and treat the track as completed.
			pass

	def addTimeline(self, timeline):
		# TODO: translate entire timeline into MIDI
		# difficulties: need to handle degree/transpose params
		#			   need to handle channels properly, and reset numtracks
		pass

	def writeFile(self, filename = "score.mid"):
		fd = open(filename, 'wb')
		self.score.writeFile(fd)
		fd.close()
예제 #3
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()
예제 #4
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)
예제 #5
0
파일: midi.py 프로젝트: Nospoko/blompf
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)
예제 #6
0
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"
예제 #7
0
파일: outputs.py 프로젝트: shish/mic2midi
    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)
예제 #8
0
파일: solfeggio.py 프로젝트: mnvl/solfeggio
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()
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()    
예제 #10
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
예제 #11
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()
예제 #12
0
파일: composer.py 프로젝트: sagnew/Vireo
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
예제 #13
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)
예제 #14
0
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
예제 #15
0
파일: midifile.py 프로젝트: gurk/isobar
class PatternWriterMIDI:
	def __init__(self, numtracks = 1):
		self.score = MIDIFile(numtracks)
		self.track = 0
		self.channel = 0
		self.volume = 64

	def addTrack(self, pattern, tracknumber = 0, trackname = "track", dur = 1.0):
		time = 0
		# naive approach: assume every duration is 1
		# TODO: accept dicts or PDicts
		for note in pattern:
			if note is not None:
				self.score.addNote(tracknumber, self.channel, note, time, dur, self.volume)
				time += dur
			else:
				time += dur

	def addTimeline(self, timeline):
		# TODO: translate entire timeline into MIDI
		# difficulties: need to handle degree/transpose params
		#			   need to handle channels properly, and reset numtracks
		pass

	def writeFile(self, filename = "score.mid"):
		fd = open(filename, 'wb')
		self.score.writeFile(fd)
		fd.close()
예제 #16
0
파일: midifile.py 프로젝트: gurk/isobar
class MidiFileOut:
	def __init__(self, numtracks = 16):
		self.score = MIDIFile(numtracks)
		self.track = 0
		self.channel = 0
		self.volume = 64
		self.time = 0

	def tick(self, ticklen):
		self.time += ticklen

	def noteOn(self, note = 60, velocity = 64, channel = 0, duration = 1):
		#------------------------------------------------------------------------
		# avoid rounding errors
		#------------------------------------------------------------------------
		time = round(self.time, 5)
		self.score.addNote(channel, channel, note, time, duration, velocity)

	def noteOff(self, note = 60, channel = 0):
		pass

	def writeFile(self, filename = "score.mid"):
		fd = open(filename, 'wb')
		self.score.writeFile(fd)
		fd.close()
예제 #17
0
class MidiFileOut:
    """ Write events to a MIDI file.
        Requires the MIDIUtil package:
        https://code.google.com/p/midiutil/ """

    def __init__(self, filename = "score.mid", num_tracks = 16):
        from midiutil.MidiFile import MIDIFile

        self.filename = filename
        self.score = MIDIFile(num_tracks)
        self.time = 0

    def tick(self, tick_length):
        self.time += tick_length

    def note_on(self, note = 60, velocity = 64, channel = 0, duration = 1):
        #------------------------------------------------------------------------
        # avoid rounding errors
        #------------------------------------------------------------------------
        time = round(self.time, 5)
        self.score.addNote(channel, channel, note, time, duration, velocity)

    def note_off(self, note = 60, channel = 0):
        time = round(self.time, 5)
        self.score.addNote(channel, channel, note, time, 0, 0)

    def write(self):
        fd = open(self.filename, 'wb')
        self.score.writeFile(fd)
        fd.close()
예제 #18
0
파일: gabctk.py 프로젝트: jperon/gabctk
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)
예제 #19
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()
예제 #20
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()
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)
예제 #22
0
파일: midigen.py 프로젝트: alldne/midigen
def main():
    if len(sys.argv) is 1:
        return
    song_descriptor_path = sys.argv[1]
    with open(song_descriptor_path, 'r') as f:
        read_data = f.read()
    song_descriptor = json.loads(read_data)
    midi_file = MIDIFile(len(song_descriptor['tracks']))
    for track in song_descriptor['tracks']:
        make_midi(midi_file, track)

    with open("test.mid", 'wb') as outf:
        midi_file.writeFile(outf)
예제 #23
0
파일: utils.py 프로젝트: Alligator/evo
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()
예제 #24
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()
예제 #25
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()
예제 #26
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()
예제 #27
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()
예제 #28
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()
예제 #29
0
def write_song(song, dest, tempo=240):
    num_channels = len(song)
    midi_scratch_file = MIDIFile(num_channels)
    for i in range(0, num_channels):
        midi_scratch_file.addTrackName(i, 0, "Pop Flute {0}".format(i))
        midi_scratch_file.addTempo(i, 0, tempo)
        time = 0
        for x in range(0, song_length(song)):
            duration = 0.5
            pitch = song[i][x]
            midi_scratch_file.addNote(i, i, pitch, time, duration, 100)
            time += duration

    bin_file = open(dest, 'w')
    midi_scratch_file.writeFile(bin_file)
    bin_file.close()
예제 #30
0
    def export_midi(self, file_path):
        """Export a MIDI file."""
        midi = MIDIFile(1)
        midi.addTrackName(0, 0, self.metadata.get('OTL'))
        midi.addTempo(0, 0, 80)

        for i, part in enumerate(self.parts):
            non_rests = [ d for d in part['data'] if d['pitch'] != 'r' ]
            for note in non_rests:
                midi.addNote(track=0, channel=i,
                             pitch=note['midinote'],
                             time=note['beat'],
                             duration=note['duration'],
                             volume=80)

        with open(file_path, 'wb') as binfile:
            midi.writeFile(binfile)
예제 #31
0
def pixels_to_midi(pix, img_string):
    mf = MIDIFile(1)
    track = 0
    time = 0
    channel = 0
    volume = 100
    mf.addTrackName(track, time, "Sample")
    mf.addTempo(track, time, 1000)
    for i in pix:
        p2 = rgb_to_midi(i[1])
        p3 = rgb_to_midi(i[2])
        duration = 1
        if time % 4 == 0:
            mf.addNote(track, channel, p2, time, 4, volume)
            mf.addNote(track, channel, p3, time, 4, volume)
        else:
            mf.addNote(track, channel, p3, time, duration, volume)
        time += 1
    with open(img_string, 'wb') as outf:
        mf.writeFile(outf)
예제 #32
0
    def writeMidi():
        #print(population)
        channel = 0
        track = 0
        time = 0
        for i in population:
            mf = MIDIFile(numTracks = 1, adjust_origin=True)
            mf.addTrackName(track, time, 'main')
            mf.addTempo(track, time, 240)
            #print(i)
            for note in population[i]:
                pitch = population[i][note]['pitch']
                time = population[i][note]['start']
                duration = population[i][note]['duration'] / 10
                velocity = int((population[i][note]['velocity'])*100)
                mf.addNote(channel, track, pitch, time, duration, velocity)


            with open("./midiOut/output" + str(i) + ".mid", "wb") as outf:
                mf.writeFile(outf)
예제 #33
0
def main_out():
    MyMIDI = MIDIFile(1)

    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)

    binfile = open("output.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
예제 #34
0
class MidiParser:
    def __init__(self, numberOfTracks, tempo, volume=100, channel=0):
        self.numberOfTracks = numberOfTracks
        self.tempo = tempo
        self.volume = volume
        self.channel = channel

        self.midiFile = MIDIFile(numberOfTracks)

        for i in range(self.numberOfTracks - 1):
            self.midiFile.addTrackName(i, 0, "Track " + str(i + 1))
            self.midiFile.addTempo(i, 0, self.tempo)

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

    def exportFile(self, filename):
        with open(filename, 'wb') as exportFile:
            self.midiFile.writeFile(exportFile)
예제 #35
0
def midiMaker (tempHome):
    # 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")
    mf.addTempo(track, time, 120)

    # add some notes
    channel = 0
    volume = 100

    pitch = 60           # C4 (middle C)
    time = 0             # start on beat 0
    duration = 0.5       # 1 beat long
    mf.addNote(track, channel, pitch, time, duration, volume)

    pitch = 64           # E4
    time = 2             # start on beat 2
    duration = 1         # 1 beat long
    mf.addNote(track, channel, pitch, time, duration, volume)

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

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


    # write it to disk
    funcRawName =input("Give a name for the file: ")
    funcFileName = funcRawName + ".mid"
    outFile = tempHome +"/"+funcFileName
    with open(outFile, 'wb') as outf:
        mf.writeFile(outf)
    return funcRawName
예제 #36
0
def convert_midi(song, file_name):
    mf = MIDIFile(1)
    track = 0
    time = 0
    mf.addTrackName(track, time, "Music")
    mf.addTempo(track, time, 60)
    channel = 0
    volume = 120

    for elem in song:
        if elem.dlit == "note-half":
            duration = 0.5
        else:
            duration = 0.25

        pitch = key[elem.name]
        mf.addNote(track, channel, pitch, time, duration, volume)
        time = time + duration

    with open(file_name + '.mid', 'wb') as outf:
        mf.writeFile(outf)
예제 #37
0
    def write_to_midi(self, midi_time_frames, tempo=60):
        mf = MIDIFile(1)
        track = 0
        time = 0
        tempo_multiplier = 60/tempo
        mf.addTrackName(track, time, 'Marimba')
        mf.addTempo(track, time, tempo)

        channel = 0
        volume = 100
        beat = 1

        for tf in midi_time_frames:
            if tf['note'] > 0:
                # breakpoint()
                print(f"Adding note {tf['note']} starting at {beat} lasting for {1} beat")
                mf.addNote(track, channel, tf['note'], beat, 1, volume)
                beat += 1

        with open('output.mid', 'wb') as outf:
            mf.writeFile(outf)            
예제 #38
0
def MIDI_VV():
    mf = MIDIFile(3)  #3 tracks
    startTime = 0  #begint bij het begin
    track = 0
    mf.addTrackName(track, startTime, "5/4 Beat")
    mf.addTempo(track, startTime, BPM)
    if len(noteLengths1_VV) == 0:
        print("Kick Done")
        #write to disk
        with open("output.mid", 'wb') as outf:
            mf.writeFile(outf)
    else:
        track = 0  #eerste track
        channel = 10  #percussie
        volume = 100
        pitch = 35  #kick
        time = 0  #startpunt noot
        duration = noteLengths1_VV.pop(0)  #1e nootlengte uit de lijst
        mf.addNote(track, channel, pitch, time, duration, volume)
        print(mf)
        return MIDI_VV()
def save_midi(outfile, notes, tempo):
    track = 0
    time = 0
    midifile = MIDIFile(1)

    midifile.addTrackName(track, time, "MIDI TRACK")
    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])
        midifile.addNote(track, channel, pitch, onset, duration, volume)

    binfile = open(outfile, 'wb')
    midifile.writeFile(binfile)
    binfile.close()
예제 #40
0
    def output_midi(self) -> None:
        midi = MIDIFile(1)

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

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

        for note in self._notes:
            duration = note.length.value * 4  # TODO: DRY
            midi.addNote(track, channel, note.pitch.value, time, duration,
                         volume)
            time += duration

        midi_file = open('output.mid', 'wb')
        midi.writeFile(midi_file)
        midi_file.close()
        open_file('output.mid')
예제 #41
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)
예제 #42
0
class MidiWriter:
    def __init__(self, track_name, filepath, bpm=120):
        """
        Wraper around MIDIFile
        :param track_name: Track name
        :param bpm: Beat per minute, default=120
        """
        self.__midi_file = MIDIFile(1, adjust_origin=0)  # Single track
        self.__track = 0
        time = 0

        self.__track_name = track_name
        self.__midi_file.addTrackName(self.__track, time, self.__track_name)

        self.__midi_file.addTempo(self.__track, time, bpm)
        self.__channel = 0
        self.__filepath = filepath

    def write(self, note):
        """
        Add a note to the midi file
        :param note: note object to be added
        :return: None
        """
        duration = note.duration_tick
        if duration == 0:
            duration = 1
        for pitch in note.pitch_id:
            self.__midi_file.addNote(self.__track, self.__channel, pitch,
                                     note.start_time_tick, duration,
                                     note.volume)

    def close(self):
        """
        Write out the midi file
        :return: None
        """
        print(self.__filepath)
        with open(self.__filepath, 'wb') as out_file:
            self.__midi_file.writeFile(out_file)
예제 #43
0
class PatternWriterMIDI:
    """ Writes a pattern to a MIDI file.
        Requires the MIDIUtil package:
            https://code.google.com/p/midiutil/ """
    def __init__(self, numtracks=1):
        from midiutil.MidiFile import MIDIFile

        self.score = MIDIFile(numtracks)
        self.track = 0
        self.channel = 0
        self.volume = 64

    def addTrack(self, pattern, tracknumber=0, trackname="track", dur=1.0):
        time = 0
        # naive approach: assume every duration is 1
        # TODO: accept dicts or PDicts
        try:
            for note in pattern:
                vdur = Pattern.value(dur)
                if note is not None and vdur is not None:
                    self.score.addNote(tracknumber, self.channel, note, time,
                                       vdur, self.volume)
                    time += vdur
                else:
                    time += vdur
        except StopIteration:
            # a StopIteration exception means that an input pattern has been exhausted.
            # catch it and treat the track as completed.
            pass

    def addTimeline(self, timeline):
        # TODO: translate entire timeline into MIDI
        # difficulties: need to handle degree/transpose params
        #			   need to handle channels properly, and reset numtracks
        pass

    def writeFile(self, filename="score.mid"):
        fd = open(filename, 'wb')
        self.score.writeFile(fd)
        fd.close()
예제 #44
0
class Midi(object):
    def __init__(self, track_configs):
        self.midi_file = MIDIFile(len(track_configs))
        self.track_time = []
        for i, config in enumerate(track_configs):
            self.track_time.append(0)
            self.midi_file.addTrackName(i, config.time, config.name)
            self.midi_file.addTempo(i, config.time, config.tempo)

    def append_note(self, duration, pitches, volume=100, track=0, channel=0):
        time = self.track_time[track]
        for pitch in pitches:
            pitch += constants.C3
            self.midi_file.addNote(track, channel, pitch, time, duration,
                                   volume)
        self.track_time[track] += duration
        return time

    def write_file(self, filename):
        binfile = open(filename, 'wb')
        self.midi_file.writeFile(binfile)
        binfile.close()
예제 #45
0
def contours_to_sounds(all_init_notes, all_contours, keys, moods):
    # len of moods must be same as other lists! NOT CHECKED!
    # ALSO not checked value!
    # mood: 1 - happy, 0 - neutral, -1 - sad, -2 - sudden sad
    # right now: 1 == 0 and -1 == -2

    l = len(all_init_notes)

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

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

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

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

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

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

        with open(outfile_name, 'wb') as output_file:
            MyMIDI.writeFile(output_file)
예제 #46
0
def data_to_midi(data, output_name):
    """Generates .mid chord sequences corresponding to the given array.
	Writes the ouptut to midi files.

	Parameters
	----------
		data : numpy array
			For each time step, a list of the Midi pitches of the corresponding chord.
		output_name : str
			A name for this chord's file.

	Returns
	-------
		None.
		Writes generated sequence to disk.

	"""

    # create the MIDI object
    mf = MIDIFile(1)  # only 1 track
    track = 0  # the only track
    channel = 0
    global_tempo = 60

    time = 0  # start at the beginning of the track on beat 0
    mf.addTrackName(track, time, "Sample Track")
    mf.addTempo(track, time, global_tempo)

    for idx, val in enumerate(data):

        if val == 1:
            # add the note
            # 1 is the duration of the note
            # 100 is the volume
            mf.addNote(track, channel, idx, time, 1, 100)

    # finally, write sequence to disk
    with open(output_name, 'wb') as outf:
        mf.writeFile(outf)
def generate(n, program, suffix, sf = "/usr/share/sounds/sf2/FluidR3_GM.sf2", volume = 100):
	MyMIDI = MIDIFile(2)
	track = 0   
	time = 0
	MyMIDI.addTrackName(track,time,"Test")
	MyMIDI.addTempo(track,time,30)
	track = 0
	channel = 0
	time = 0
	duration = 2.0
	MyMIDI.addProgramChange(track, channel, 0, program)
	MyMIDI.addNote(track,channel, plist[n], 0,duration,volume)
	binfile = open("output.mid", 'wb')
	MyMIDI.writeFile(binfile)
	binfile.close()

	os.system("fluidsynth %s output.mid -F output.wav --sample-rate 1000"  % sf)
	os.system("lame -V 7 output.wav sound%d%s.mp3" % (n, suffix))
#	os.system("avconv -i output.wav  -acodec sound%d%s.aac" % (n, suffix))
	os.system("rm output.mid")
#	os.system("mplayer output.wav")
	os.system("mv output.wav sound%d%s.wav" % (n, suffix))
예제 #48
0
def make_midi_file():

    midi_file = MIDIFile()
    midi_file = populate(midi_file)
    #    midi_file.addTrackName(track, time, track_name)
    #    midi_file.addTimeSignature(track, time, numerator, denominator, clocks_per_tick, notes_per_quarter=8)
    #    midi_file.addTempo(track, time, tempo)
    #    midi_file.addKeySignature(track, time, accidentals, accidental_type, mode, insertion_order=0)
    #    midi_file.addCopyright(track, time, notice)
    #
    #    track    = 0   # Track numbers are zero-origined
    #    channel  = 0   # MIDI channel number
    #    pitch    = 60  # MIDI note number
    #    time     = 0   # In beats
    #    duration = 1   # In beats
    #    volume   = 100 # 0-127, 127 being full volume

    filename = "basshit.midi"

    with open(filename, "wb") as output_file:

        midi_file.writeFile(output_file)
예제 #49
0
def prepare_initial_midi(text, out, tempo):
    midi = MIDIFile(1)
    midi.addTempo(track=0, time=0, tempo=tempo)
    midiText = open(text)
    duration = -1
    pitch = volume = time = -1
    for line in midiText:
        line = line.rstrip()
        m = LINE_REGEX.search(line)
        if m.group("on_off") == "On":
            pitch = int(m.group("pitch"))
            volume = int(m.group("volume"))
            time = int(m.group("time"))
            duration = time
        else:
            time2 = int(m.group("time"))
            duration = (float(time2) - float(time))
            midi.addNote(0, 0, pitch, time, duration, volume)
            #                print "Added p: %d t: %d d: %f v: %d" % (pitch,time,duration,volume)
            duration = -1
    midi.writeFile(open(out, "w"))
    return midi
예제 #50
0
def crf_midi_generator(X, Z, n, m, silence, note_length):
    track = 0
    channel = 0
    volume = 100
    MyMIDI = MIDIFile(3)
    label_track = 0
    prediction_track = 1
    time = 0
    tempo = 60
    MyMIDI.addTempo(track, time, tempo)
    print(Z["out"][m])
    print(X.shape)
    count = 0
    total = 0
    current_time = 0
    for i, item in enumerate(X):
        if (i >= len(Z['out'][m])):
            continue
        duration = float(item[0])
        time = current_time
        current_time += duration
        #time = i
        #duration = 1
        pitch = int(item[2])
        print(pitch)
        MyMIDI.addNote(track, channel, pitch, time, duration, volume)
        flag = int(Z["out"][m][i])
        if (flag == 1):
            MyMIDI.addNote(prediction_track, channel, 30, time, duration,
                           volume)
            #print(X[n][i-1][1]-X[n][i-1][0], X[n][i][0]-X[n][i-1][1])
            if i > 0 and (X[i - 1][1] - X[i - 1][0]) < note_length and (
                    X[i][0] - X[i - 1][1]) < silence:
                count += 1
    path = "/Users/joker/sample" + str(n) + "_" + str(m) + ".mid"
    midifile = open(path, "wb")
    MyMIDI.writeFile(midifile)
    midifile.close()
    return count, total
예제 #51
0
def pixels_to_midi():
    pix = get_image_data("green.jpg")
    mf = MIDIFile(1)
    track = 0
    time = 0
    channel = 0
    volume = 100
    mf.addTrackName(track, time, "Sample")
    mf.addTempo(track, time, 1000)
    for i in pix:
        p2 = rgb_to_midi(i[1])
        p3 = rgb_to_midi(i[2])
        duration = 1
        if time % 4 == 0:
            mf.addNote(track, channel, p2, time, 4, volume)
            mf.addNote(track, channel, p3, time, 4, volume)
        else:
            mf.addNote(track, channel, p3, time, duration, volume)
        time += 1
    print "done"
    with open("green.mid", 'wb') as outf:
        mf.writeFile(outf)
def write_gui_song(song, gui_tempo, name="gui_song.mid"):

    MyMIDI = MIDIFile(1) # One track
    file = open("gui_notes_data.txt", "w+")
    track = 0
    channel = 0
    time = 0 # time in beats
    tempo = gui_tempo # tempo of the song
    volume = 120 # volume of the note

    MyMIDI.addTempo(track, time, tempo)

    for phrase in song:
        for measure in phrase:
            for note in measure:
                # Add the new note into the MIDI object
                # Note tuple structure: (note_start_time, note_value, note_length)
                MyMIDI.addNote(track, channel, note[1], note[0], note[2], volume)
                file.write("%.2f %d %.2f \n" % (note[0], note[1], note[2]))

    with open(name, "wb") as output_file:
        MyMIDI.writeFile(output_file)
예제 #53
0
def save_midi(outfile, notes, tempo):
    track = 0
    time = 0
    midifile = MIDIFile(1)

    # Add track name and tempo.
    midifile.addTrackName(track, time, 'MIDI TRACK')
    midifile.addTempo(track, time, tempo)

    channel = 0
    volume = 100

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

    # And write it to disk.
    binfile = open(outfile, 'wb')
    midifile.writeFile(binfile)
    binfile.close()
예제 #54
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)
예제 #55
0
def TXT_to_MIDI(txtfile):
    sensors = 7 #number of instruments, assume organized by columns
    file = open (txtfile, 'r')
    data = []
    for line in file:
        data.append([float(x) for x in line.split()])
    size=len(data)
    mf = MIDIFile(sensors) #can make two channels, but starting with 1
    volume = 100
    duration = 1 #can make variable, right now 1 beat
    channel = 0 #1-16 MIDI channels, keeping all on one for now
    tempo = 60 #BPM
    for inst in range(sensors):
        track = inst
        mf.addTempo(track, time, tempo)
        for i in range(len(data[inst])):
            currentData = data[inst][i]
            pitch = data_to_pitch(currentData, duration, volume)
            mf.addNote(track, channel, pitch, i, duration, volume) #i==time


    with open('output8.mid', 'wb') as output_file:
        mf.writeFile(output_file)
예제 #56
0
 def convert_to_MIDI(self, title):
     mf = MIDIFile(1, adjust_origin=False)
     track = 0
     time = 0
     mf.addTrackName(track, time, title)
     mf.addTempo(track, time, 120)
     for pos in range(self.num_notes):
         for pitch in range(self.note_range):
             if self.grid[pos][pitch]:
                 duration = 1
                 next_cell = None
                 if pos + duration < self.num_notes:
                     next_cell = self.grid[pos + duration][pitch]
                 while next_cell is not None and not next_cell:
                     duration += 1
                     if pos + duration < self.num_notes:
                         next_cell = self.grid[pos + duration][pitch]
                     else:
                         next_cell = None
                 mf.addNote(0, 0, pitch + self.lowest_note, pos, duration,
                            60)
     with open(title, 'wb') as outf:
         mf.writeFile(outf)
예제 #57
0
def writeToMidi(title, tempo, notes):

    # open up the media file.
    mf = MIDIFile(1, adjust_origin=1)

    track = 0
    time = 0.0
    temptime = 0
    channel = 0
    volume = 100

    # initialize the first track.
    mf.addTrackName(track, time, title)
    mf.addTempo(track, time, tempo * 16)

    # notes should be a list of lists, with notes in the
    # sub lists occuring at the same time.
    for chord in notes:
        for sound in chord:

            # save the time interval for the notes.
            # they should all be the same within the chord.

            # vprint(sound)

            # temptime = sound["time"]

            # add the note to the midi track if its not a rest
            if (sound['note'] != 'R'):
                mf.addNote(track, channel, MIDIpitch(sound['note'], sound['octave']), \
                        sound['time'], sound['length'], sound['volume'])

        # increase the time counter
        # time += temptime

    with open(title, 'wb') as outf:
        mf.writeFile(outf)
예제 #58
0
def _createRawMIDI(filename, clips):
    channel = 0
    track = 0
    tempo = 60
    volume = 100
    time = 0
    outfile = MIDIFile(1)
    outfile.addTempo(track, time, tempo)
    for clip in clips:
        channel = (channel + 1) % 16
        for note in clip.notes:
            print(note.time)
            print(note.duration)
            print(note.pitch)
            print(clip.startTime)
            time = int(note.time) + int(clip.startTime)
            print("Oh")
            duration = note.duration
            pitch = note.pitch
            print("About to out")
            print(track)
            print(channel)
            print(pitch)
            print(time)
            print(duration)
            print(volume)
            outfile.addNote(int(track), int(channel), int(pitch), int(time),
                            int(duration), int(volume))
            print("Outing")
    print("Still unwritten")
    with open(filename, "wb") as written_file:
        print(type(filename))
        print(type(outfile))
        print(type(written_file))
        outfile.writeFile(written_file)
        print("Almost Written")
    print("Not unwritten")
예제 #59
0
def generate_midi(audiofile):
    # Create the MIDIFile Object with 1 track
    MyMIDI = MIDIFile(1)

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

    print "Tempo:", audiofile.analysis.tempo

    # Add track name and tempo.
    MyMIDI.addTrackName(track, time, "Sample Track")
    MyMIDI.addTempo(track, time, audiofile.analysis.tempo["value"])

    durations = numpy.array([p.duration for p in audiofile.analysis.segments])
    segment_end_times = numpy.cumsum(durations)
    segment_start_times = segment_end_times - durations

    normalized_loudness = normalize_loudness(audiofile)

    track = 0
    channel = 0
    for i in range(len(audiofile.analysis.segments)):
        for j in range(12):
            pitch = j + 60
            time = segment_start_times[i]
            duration = durations[i]
            volume = int(normalized_loudness[i] *
                         audiofile.analysis.segments[i].pitches[j] * 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()
예제 #60
0
def midisaver():
    print(
        "s = Save         n = New Sequence        q = Quit            p=Pause/Play"
    )
    while True:
        choice = input("> ")
        if choice == 's':
            oldvoices = list(voices)
            mf = MIDIFile(5, deinterleave=False)
            time = 0
            for i in range(4):
                mf.addTrackName(i, 0, tracknames[i])
                mf.addTempo(i, 0, bpm)
                channel = 0
                for x in range(len(oldvoices[i])):
                    if isinstance(oldvoices[i][x][1], int):
                        oldvoices[i][x][1] = [oldvoices[i][x][1]]
                    for pitch in oldvoices[i][x][1]:
                        if pitch != 0:
                            volume = oldvoices[i][x][2]
                            time = oldvoices[i][x][
                                0] / 4  #convert from beats to sixteenths
                            if time + 1 < 8:
                                duration = oldvoices[i][x][3] / 4
                            else:
                                duration = 0.1
                            mf.addNote(i, channel, pitch, time, duration,
                                       volume)
            filename = (input('Save As:') + ".mid")
            with open(filename, 'wb') as outf:
                mf.writeFile(outf)
        if choice == 'q':
            thread.interrupt_main()
            sys.exit()
        if choice == 'n':
            measureCount = 0
            compose()