本文整理汇总了Python中midiutil.MidiFile.MIDIFile.writeFile方法的典型用法代码示例。如果您正苦于以下问题:Python MIDIFile.writeFile方法的具体用法?Python MIDIFile.writeFile怎么用?Python MIDIFile.writeFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类midiutil.MidiFile.MIDIFile
的用法示例。
在下文中一共展示了MIDIFile.writeFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: savefile
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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: MidiFileCreator
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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"
示例3: saveMIDI
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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()
示例4: make_song_file
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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()
示例5: write_midi_file
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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)
示例6: render
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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
示例7: play
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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)
示例8: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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()
示例9: matrix_to_midi
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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)
示例10: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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()
示例11: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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()
示例12: midFile
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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()
示例14: FileOutput
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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)
示例15: convert_to_song
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import writeFile [as 别名]
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()