本文整理汇总了Python中midi.write_midifile函数的典型用法代码示例。如果您正苦于以下问题:Python write_midifile函数的具体用法?Python write_midifile怎么用?Python write_midifile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write_midifile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
usage = "%prog [options] <in-file>"
description = "Play music using the Harmonical. This allows you to "\
"play music specified precisely in the tonal space. By default, "\
"plays back the input, but can also output to a file."
parser = OptionParser(usage=usage, description=description)
parser.add_option('-o', '--output', dest="outfile", action="store", help="output the result to a wave file instead of playing back.")
parser.add_option('-m', '--midi', dest="midi", action="store_true", help="generate midi data, not audio. Depends on the input format supporting midi file generation.")
options, arguments = parse_args_with_config(parser)
filename = arguments[0]
# Load up the input file
infile = HarmonicalInputFile.from_file(filename)
if options.midi:
midi = infile.render_midi()
if options.outfile is not None:
# Output a midi file
write_midifile(midi, options.outfile)
print >>sys.stderr, "Saved midi data to %s" % options.outfile
else:
print >>sys.stderr, "Playing..."
play_stream(midi, block=True)
else:
print >>sys.stderr, "Generating audio..."
audio = infile.render()
if options.outfile is not None:
# Output to a file instead of playing
save_wave_data(audio, options.outfile)
print >>sys.stderr, "Saved data to %s" % options.outfile
else:
print >>sys.stderr, "Playing..."
play_audio(audio, wait_for_end=True)
示例2: main
def main():
usage = "%prog [options] <corpus-filename> <out-filename>"
description = "Produces a MIDI file from one of the files of the "\
"Kostka-Payne corpus compiled by David Temperley. "\
"<corpus-filename> may be either a path to the file or the "\
"name of a file in the corpus (which is stored within the project)."
parser = OptionParser(description=description, usage=usage)
options, arguments = parser.parse_args()
if len(arguments) < 1:
print >>sys.stderr, "You must specify an input filename"
sys.exit(1)
elif len(arguments) < 2:
print >>sys.stderr, "You must specify an output midifile name"
sys.exit(1)
filename = arguments[0]
outname = arguments[1]
# Read in the input file
seq = DataSequence.from_file(filename)
# Produce a midi stream from the data sequence
mid = seq.to_midi()
# Output the midi file
write_midifile(mid, outname)
示例3: NoteListToMIDI
def NoteListToMIDI(filename, note_list, num_aksharam, swaras_per_aksharam):
# pattern = midi.read_midifile(filename)
MIDI_note_list = []
MIDI_note_list.append(midi.TrackNameEvent(tick = 0, text = 'Rakesh', data = [70, 76, 32, 75, 101, 121, 115, 32, 49]))
for i in note_list:
if i.MIDINote == 0:
event = midi.NoteOnEvent(tick = 0, channel = 0, data = [i.MIDINote, 0])
else:
event = midi.NoteOnEvent(tick = 0, channel = 0, data = [i.MIDINote, 100])
MIDI_note_list.append(event)
if i.MIDINote == 0:
event = midi.NoteOffEvent(tick = int(24*i.NoteLength), channel = 0, data = [i.MIDINote, 0])
else:
event = midi.NoteOffEvent(tick = int(24*i.NoteLength), channel = 0, data = [i.MIDINote, 100])
MIDI_note_list.append(event)
MIDI_note_list.append(midi.EndOfTrackEvent(tick=0, data = []))
songpattern = midi.Pattern(format = 1, resolution = 96, tracks = \
[midi.Track([midi.SetTempoEvent(tick = 0, data = [12, 53, 0]),
midi.TimeSignatureEvent(tick=0, data=[num_aksharam, swaras_per_aksharam/2, 24, 8]), midi.EndOfTrackEvent(tick=0, data = [])]),
midi.Track(MIDI_note_list)])
midi.write_midifile(filename, songpattern)
示例4: handle_drum_track
def handle_drum_track(track, prefix, channel):
print "Creating %s*.mid for channel %d" % (prefix, channel)
track.make_ticks_abs()
drumset = set()
drumhash = {}
for event in track:
event.channel = channel
if isinstance(event, midi.NoteOnEvent):
drumset.add(event.data[0])
for note in drumset:
drumhash[note] = midi.Pattern(resolution=mf.resolution)
_track = midi.Track()
drumhash[note].append(_track)
for event in track:
if isinstance(event, midi.NoteEvent):
drumhash[event.pitch][0].append(event.copy())
elif not isinstance(event, midi.EndOfTrackEvent):
for key in drumhash:
drumhash[key][0].append(eval(repr(event)))
for key in drumhash:
fn = "%s%d.mid" % (prefix, key)
drumhash[key].make_ticks_rel()
midi.write_midifile(fn, drumhash[key])
示例5: main
def main():
db = MidiDB();
records = db.records_in_key("C")
result_pattern = midi.Pattern(resolution=480)
songs = []
for i in range(5):
uid = random.choice(records)["id"];
pattern = db.pattern(uid)
midiutil.pattern_to_resolution(pattern, 480)
track = random.choice(pattern)
result_pattern.append(track)
songs.append(pattern)
remapper = midiremap.MidiRemapper("b0rkestra_description.json", result_pattern)
remapper.remap_pattern(result_pattern)
midi.write_midifile("test.mid", result_pattern)
示例6: midiExport
def midiExport(self, mainWindowInstance):
filename = QtGui.QFileDialog.getSaveFileName(filter="*.mid")
try:
if filename:
with open(filename, "wb") as f:
try:
outputPattern = midiwrite.Pattern()
outputTrack = midiwrite.Track()
eventList = []
trackName = "MeeBlip Patch"
trackNameEvent = midiwrite.TrackNameEvent(name=trackName)
eventList.append(trackNameEvent)
for index in (k for k in xrange(48, 80) if k not in range(56, 58) + range(62, 65)):
ccEvent = midiwrite.ControlChangeEvent(channel=1)
ccEvent.set_control(index)
ccEvent.set_value(self.currentPatch.patchCCDict[index])
eventList.append(ccEvent)
for event in eventList:
outputTrack.append(event)
outputPattern.append(outputTrack)
midiwrite.write_midifile(f, outputPattern)
except IOError as (errno, strerror):
QtGui.QMessageBox.warning(mainWindowInstance, "File write error: %s" % errno,
"Error writing file %s:\n %s" % (unicode(filename), unicode(strerror)))
except:
QtGui.QMessageBox.warning(mainWindowInstance, "File write error", "Unknown error writing to file.")
示例7: write_to_midi
def write_to_midi(self, filename):
"""
Resolution is 220 ticks per quarter note
"""
pattern = midi.Pattern()
track = midi.Track([], False)
bass_track = midi.Track([], False)
offset = 0
for phrase in self.phrases:
for note in phrase.melody:
if note.pitch == "rest":
offset += 110*note.rhythm
else:
track.append(midi.NoteOnEvent(tick=offset, velocity=120, pitch=self.tonic_pitch+24+note.pitch))
track.append(midi.NoteOffEvent(tick=(110*note.rhythm), pitch=self.tonic_pitch+24+note.pitch))
offset = 0
for bass_note in phrase.bass_notes:
bass_track.append(midi.NoteOnEvent(tick=0, velocity=120, pitch=self.tonic_pitch+bass_note))
bass_track.append(midi.NoteOffEvent(tick=220 * self.beats_per_measure, pitch=self.tonic_pitch+bass_note))
track.append(midi.EndOfTrackEvent(tick=1))
bass_track.append(midi.EndOfTrackEvent(tick=1))
pattern.append(track)
pattern.append(bass_track)
midi.write_midifile(filename, pattern)
示例8: main
def main(argc, argv):
if argc != 3:
print("Usage: python csv2midi.py <csv file> <output file name>")
exit(1)
# Pattern is the midi file. It can contain multiple tracks,
# but we are using just one.
pattern = midi.Pattern()
track = midi.Track()
pattern.append(track)
print(argv[1])
csvfile = open(argv[1], 'rb')
counter = 0
for row in csvfile:
print(counter)
vals = [x.strip() for x in row.split(',')]
print(vals)
vals = filter(None, vals)
vals = map(lambda x: int(x), vals)
tick = vals[0]
base = vals[1] + 60
print(len(vals))
offsets = vals[2:]
for i in range(0, len(offsets)):
offsets[i] = int(offsets[i]) + base
#print tick
#print base
#print offsets
data = []
track.append(midi.NoteOnEvent(tick=12, channel=1, data=[base] + [110]))
for x in offsets:
track.append(midi.NoteOnEvent(tick=0, channel=1, data=[x]+[110]))
track.append(midi.NoteOffEvent(tick=tick, channel=1, data=[base] + [0]))
for x in offsets:
track.append(midi.NoteOffEvent(tick=0, channel=1, data=[x]+[0]))
counter += 10
# End of track appears 1 tick after last event
track.append(midi.EndOfTrackEvent(tick=1))
print("###########################################")
print("ORIGINAL")
print("###########################################")
#pattern2 = midi.read_midifile("vexation.mid")
#print(pattern2)
#print("###########################################")
#print("RECOVERED")
#print("###########################################")
#print pattern
midi.write_midifile(argv[2], pattern)
示例9: write
def write(self):
eot = midi.EndOfTrackEvent()
eot.tick = self.delta_tick()
self.track.append(eot)
meta_track = self.make_meta_track()
pattern = midi.Pattern(tracks = [meta_track, self.track],
resolution = math.ceil(self.subres * self.subdivision / 4.0))
midi.write_midifile(self.filename, pattern)
示例10: render
def render(self):
# Add the end of track event, append it to the track
eot = midi.EndOfTrackEvent(tick=1)
self.track.append(eot)
# Print out the pattern
print self.pattern
# Save the pattern to disk
midi.write_midifile("example.mid", self.pattern)
示例11: main
def main():
usage = "%prog [options] <input-midi> <output-filename>"
description = "Cleans up a midi file by getting rid of a load of "\
"stuff that makes the music sound good, but isn't needed "\
"by our algorithms. See options for details."
parser = OptionParser(usage=usage, description=description)
parser.add_option('-d', '--remove-drums', dest="remove_drums", action="store_true", help="filter out drum tracks", default=False)
parser.add_option('-p', '--pc', '--remove-program-change', dest="remove_pc", action="store_true", help="filter out all program change (instrument) events", default=False)
parser.add_option('-x', '--remove-text', '--txt', dest="remove_text", action="store_true", help="filter out all text events of any type", default=False)
parser.add_option('-o', '--one-track', dest="one_track", action="store_true", help="reduce everything down to one track", default=False)
parser.add_option('-t', '--remove-tempo', dest="remove_tempo", action="store_true", help="remove all tempo events", default=False)
parser.add_option('-c', '--remove-control', dest="remove_control", action="store_true", help="remove all control change events", default=False)
parser.add_option('--ch', '--one-channel', dest="one_channel", action="store_true", help="use only one channel: every event occurs on channel 0", default=False)
parser.add_option('--mc', '--remove-misc-control', dest="remove_misc_control", action="store_true", help="filter out a whole load of device control events: aftertouch, channel aftertouch, pitch wheel, sysex, port", default=False)
parser.add_option('--rno', '--real-note-offs', dest="real_note_offs", action="store_true", help="replace 0-velocity note-ons with actual note-offs. Some midi files use one, some the other", default=False)
parser.add_option('--remove-duplicates', dest="remove_duplicates", action="store_true", help="tidy up at the end to remove any duplicate notes", default=False)
parser.add_option('-i', '--invert', dest="invert", action="store_true", help="inverts all options. I.e. applies all filters except those selected by the above options", default=False)
parser.add_option('-r', '--remove-channels', dest="remove_channels", action="append", type="int", help="filter out all events of the numbered channel. Use multiple options to filter multiple channels at once")
parser.add_option('--resolution', '--res', dest="resolution", action="store", type="int", help="change the resolution of the midi data from that read in from the file to that given")
options, arguments = parse_args_with_config(parser)
if len(arguments) < 2:
print >>sys.stderr, "You must specify an input and output filename"
sys.exit(1)
in_filename = os.path.abspath(arguments[0])
out_filename = os.path.abspath(arguments[1])
# Read in the midi file
mid = read_midifile(in_filename, force_resolution=options.resolution)
# Build a dictionary of kwargs to select what operations to apply
filters = {
'remove_drums' : options.remove_drums ^ options.invert,
'remove_pc' : options.remove_pc ^ options.invert,
'remove_all_text' : options.remove_text ^ options.invert,
'one_track' : options.one_track ^ options.invert,
'remove_tempo' : options.remove_tempo ^ options.invert,
'remove_control' : options.remove_control ^ options.invert,
'one_channel' : options.one_channel ^ options.invert,
'remove_misc_control' : options.remove_misc_control ^ options.invert,
'real_note_offs' : options.real_note_offs ^ options.invert,
}
print "Filters to be applied:"
if options.remove_channels is not None:
print " removing channels: %s" % ", ".join(str(ch) for ch in options.remove_channels)
if options.resolution is not None:
print " changing resolution to %d" % options.resolution
print "\n".join(" %s" % name for (name,val) in filters.items() if val)
filters['remove_duplicates'] = options.remove_duplicates
print "Filtering..."
# Apply channel filters first
if options.remove_channels is not None:
remove_channels(mid, options.remove_channels)
filtered = simplify(mid, **filters)
print "Midi output to",out_filename
write_midifile(filtered, out_filename)
示例12: main
def main():
composerName = "mozart"
createNewTransition = False
inputFiles = glob.glob('midis/midiworld/classic/' + composerName + '*.mid')
if createNewTransition:
getTransitionMatrix(inputFiles, composerName)
lengthM = loadMatrixFromFile("matrices/" + composerName + "LengthM.dat")
pitchM = loadMatrixFromFile("matrices/" + composerName + "PitchM.dat")
velocityM = loadMatrixFromFile("matrices/" + composerName + "VelocityM.dat")
notesList = highestPlausibility(lengthM, pitchM, velocityM)
outFileName = "midis/" + composerName + "New.mid"
# Instantiate a MIDI Pattern (contains a list of tracks)
resolution=384
pattern = midi.Pattern(resolution=resolution)
# Instantiate a MIDI Track (contains a list of MIDI events)
track = midi.Track()
# Append the track to the pattern
pattern.append(track)
# Set Instrument to piano
pEvent = midi.ProgramChangeEvent(tick=0, channel=0)
pEvent.set_value(1)
track.append(pEvent)
# Set tempo to 150 bpm
tEvent = midi.SetTempoEvent(tick=0)
tEvent.set_bpm(150)
track.append(tEvent)
for note in notesList:
tick = Note.lengthToTick(note.length, resolution)
pitch = note.pitch
velocity = note.volume
# Append the new note
track.append(midi.NoteOnEvent(channel=0, tick=0, pitch = pitch, velocity=velocity))
# Stop the previous note to avoid unpleasant mixing
track.append(midi.NoteOnEvent(channel=0, tick=tick, pitch=pitch,velocity=0))
# Add the end of track event, append it to the track
eot = midi.EndOfTrackEvent(tick=0)
track.append(eot)
print pattern
# Save the pattern to disk
midi.write_midifile(outFileName, pattern)
print "\nMusic written to " + outFileName + "\n"
示例13: sequence_to_midi
def sequence_to_midi(state_matrix, filepath, meta_info=None):
"""
Converts a state_matrix to the corresponding 'pattern'
and writes the pattern as a midi file.
:param state_matrix: The state matrix.
:type state_matrix: 2-D list
:param filepath: The path of the output midi file.
:type filepath: str
:param meta_info: Resolution and tempo-event of the pattern.
:type meta_info: (int, SetTempoEvent or None) or None
:returns: The pattern sequence corresponding to the state matrix.
:return_type: list
"""
resolution, tempo_event = meta_info if meta_info else None
pattern = midi.Pattern(resolution=resolution)
track = midi.Track()
pattern.append(track)
if tempo_event:
track.append(tempo_event)
# Append the very first tick (which will only have NoteOn events)
notes_on, _ = state_diff([0] * 128, state_matrix[0])
for note in notes_on:
track.append(midi.NoteOnEvent(tick=0, channel=0, data=note))
# Append the rest of the ticks
current_state_index = 0
while current_state_index < len(state_matrix):
next_state_index = get_next_different_state(
state_matrix, current_state_index)
ticks_elapsed = next_state_index - current_state_index
current_state = state_matrix[current_state_index]
next_state = state_matrix[next_state_index] if next_state_index < len(
state_matrix) else [0] * 128
notes_on, notes_off = state_diff(current_state, next_state)
for note in notes_on:
track.append(midi.NoteOnEvent(
tick=ticks_elapsed, channel=0, data=note))
# The rest of the events are happening simultaneously,
# so set time_elapsed (tick) = 0 for them
ticks_elapsed = 0
for note in notes_off:
track.append(midi.NoteOffEvent(
tick=ticks_elapsed, channel=0, data=note))
ticks_elapsed = 0
current_state_index = next_state_index
track.append(midi.EndOfTrackEvent(tick=1))
midi.write_midifile(filepath, pattern)
return pattern
示例14: writeDebugTrack
def writeDebugTrack(track, filename, index):
if not os.path.exists(tracks_dir):
os.makedirs(tracks_dir)
pattern = midi.Pattern()
pattern.append(track)
eot = midi.EndOfTrackEvent(tick=1)
track.append(eot)
#print "Writing debug track for "+filename+". Track #"+str(index)
#print pattern
midi.write_midifile(tracks_dir + "/" + filename + "_track"+str(index), pattern)
示例15: write
def write(self, outfile):
"""
Renders MIDI data and writes it out the the given file.
@type outfile: string or open file
@param outfile: filename to write to or an open file(-like) object
"""
mid = self.render()
write_midifile(mid, outfile)