本文整理汇总了Python中midiutil.MidiFile.MIDIFile类的典型用法代码示例。如果您正苦于以下问题:Python MIDIFile类的具体用法?Python MIDIFile怎么用?Python MIDIFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MIDIFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FileOutput
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)
示例2: __init__
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: __init__
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()
示例4: main
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)
示例5: __init__
class MidiFileOut:
""" Write events to a MIDI file.
Requires the MIDIUtil package:
https://code.google.com/p/midiutil/ """
def __init__(self, numtracks = 16):
from midiutil.MidiFile import MIDIFile
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()
示例6: export
def export(self, filename):
'Exports the project to a MIDI-file'
# entries must contain stuff
if len(self.entries) == 0:
return
# reset the midi variable
global Midi
Midi = MIDIFile(1)
Midi.addTrackName(track, time_start, 'MIDI Cuer')
# the great export loop
all_beats = int( math.ceil( self.entries[len(self.entries)-1][3] ) )
out = {}
for x in xrange(1, len(self.entries)):
out.update( self.calcIterBeats( self.entries[x-1][3], self.entries[x][3], self.entries[x-1][2], self.entries[x][2], self.stepsize ) )
for x in sorted(out.iterkeys()):
AddTempo(x, out[x])
if self.BeatExists(x):
AddNote(x)
# de-comment following 3 lines for debugging during output
# print 'Debuggin:'
# for x in sorted(out):
# print x, out[x]
SaveIt(filename)
示例7: testAddNote
def testAddNote(self):
MyMIDI = MIDIFile(1)
MyMIDI.addNote(0, 0, 100, 0, 1, 100)
self.assertEquals(MyMIDI.tracks[0].eventList[0].type, "note")
self.assertEquals(MyMIDI.tracks[0].eventList[0].pitch, 100)
self.assertEquals(MyMIDI.tracks[0].eventList[0].time, 0)
self.assertEquals(MyMIDI.tracks[0].eventList[0].duration, 1)
self.assertEquals(MyMIDI.tracks[0].eventList[0].volume, 100)
示例8: initializeTrack
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
示例9: play
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)
示例10: write_midi_file
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)
示例11: render
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
示例12: saveMIDI
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()
示例13: playMIDI
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
示例14: matrix_to_midi
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)
示例15: midFile
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