• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python midi.write_midifile函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中midi.write_midifile函数的典型用法代码示例。如果您正苦于以下问题:Python write_midifile函数的具体用法?Python write_midifile怎么用?Python write_midifile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了write_midifile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:johndpope,项目名称:jazzparser,代码行数:35,代码来源:play.py


示例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)
开发者ID:johndpope,项目名称:jazzparser,代码行数:27,代码来源:kp2midi.py


示例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)
    
开发者ID:rakeshramakrishnan,项目名称:CarnaticMusicNotation,代码行数:27,代码来源:MIDIwrite.py


示例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])
开发者ID:vishnubob,项目名称:mythonic,代码行数:26,代码来源:process_ssb.py


示例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)
开发者ID:b0rkestra,项目名称:b0rkestra,代码行数:25,代码来源:mididb.py


示例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.")
开发者ID:bitrex,项目名称:meeblip-control,代码行数:29,代码来源:windowHandler.py


示例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)
开发者ID:dannysullivan,项目名称:songer,代码行数:29,代码来源:song.py


示例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)
开发者ID:bburdette,项目名称:ChordPredictor,代码行数:59,代码来源:csv2midi.py


示例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)
开发者ID:andreasjansson,项目名称:Celltone,代码行数:8,代码来源:cellmidi.py


示例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)
开发者ID:soycode,项目名称:MoMi,代码行数:8,代码来源:momi2midi.py


示例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)
开发者ID:johndpope,项目名称:jazzparser,代码行数:57,代码来源:simplify.py


示例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"
开发者ID:pzhao1,项目名称:MusicGenerator,代码行数:57,代码来源:highestPlausibility.py


示例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
开发者ID:Anmol-Singh-Jaggi,项目名称:Jukebot,代码行数:56,代码来源:midi_sequence.py


示例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) 
开发者ID:delbalso,项目名称:midi,代码行数:10,代码来源:transcribe.py


示例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)
开发者ID:johndpope,项目名称:jazzparser,代码行数:10,代码来源:chords.py


示例16: load_stream

 def load_stream(self, stream):
     """
     Loads the whole of an L{EventStream<midi.EventStream>}.
     Call L{play} to start playback.
     
     """
     temp_file = TemporaryFile(suffix=".mid")
     write_midifile(stream, temp_file)
     temp_file.seek(0)
     mixer.music.load(temp_file)
     self._music_loaded = True
开发者ID:johndpope,项目名称:jazzparser,代码行数:11,代码来源:__init__.py


示例17: midiMap

def midiMap(attr,f_name):

    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    file_name = f_name
    print 'length = '+str(len(attr))

    for k in range(len(attr['key'])):
        # Instantiate a MIDI note on event, append it to the track
        #print "midi."+str(attr['key'][k])+"_"+str(attr['octave'][k])
        key = attr['key'][k]
        #print key
        octave = attr['octave'][k]

        #print key_names[key]
        key_number = key_names[key] + 12*(octave-1)
        #print key_number
        #pitch = eval("midi."+str(key)+"_"+str(octave))
        pitch = key_number
        #print pitch
        ed = attr['effective_duration'][k] * 500
        if k==(len(attr['key'])-1):
            timing_f = 50*ed
            timing_i = 0

        else :
            timing_f = attr['times'][k+1] * 1000
            timing_i = attr['times'][k] * 1000


        #print timing_f - timing_i
        #print "ed = " +str(ed)
        on = midi.NoteOnEvent(tick=0, velocity=70, pitch=pitch)
        track.append(on)
        off = midi.NoteOffEvent(tick=int(timing_f - timing_i - ed) , pitch=pitch)
        track.append(off)
        on = midi.NoteOnEvent(tick=1, velocity=0, pitch=pitch)
        track.append(on)        
        off = midi.NoteOffEvent(tick=1, pitch=pitch)
        track.append(off)
        
      



    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    #print pattern
    file_name = os.path.basename(file_name).split('.')[0]
    print(file_name)
    path = "recorded_to_midi/" + file_name + ".mid"
    midi.write_midifile(path, pattern)
开发者ID:vanditthakkar,项目名称:sound-assessment-toolset,代码行数:54,代码来源:midiMap.py


示例18: main

def main():
    usage = "%prog [options] <seq-file>:<index> <midi-file> <midi-out>"
    description = "Aligns a chord sequence with a MIDI file and inserts "\
        "marker events into the MIDI data to mark where chord changes "\
        "are. Alignment parameters will be loaded from a file (not "\
        "implemented yet), but can be overridden using the script's "\
        "options."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option("--mbpb", "--midi-beats-per-beat", dest="beats_per_beat", type="int", help="number of midi beats to align with a single sequence beat (see SequenceMidiAlignment.midi_beats_per_beat)")
    parser.add_option("--ss", "--sequence-start", dest="sequence_start", type="int", help="number of midi ticks after the first note-on event when the chord sequence begins (see SequenceMidiAlignment.sequence_start)")
    parser.add_option("--repeats", dest="repeats", help="repeat spans, in the form 'start_chord,end_chord,count', separated by semicolons (see SequenceMidiAlignment.repeat_spans)")
    parser.add_option("--lyrics", dest="lyrics", action="store_true", help="use lyrics events instead of marker events to mark the chords")
    options, arguments = parser.parse_args()
    
    if len(arguments) < 3:
        print "You must specify a sequence file, midi file and output midi filename"
        sys.exit(1)
        
    # Get the chord sequence
    filename,__,index = arguments[0].partition(":")
    index = int(index)
    seq = SequenceIndex.from_file(filename).sequence_by_index(index)
    
    # Load the input midi data
    mid = read_midifile(arguments[1])
    
    outfile = arguments[2]
    
    # For now, just create a new default alignment
    # TODO: load the alignment parameters from a file or from the 
    #  sequence data itself
    alignment = SequenceMidiAlignment()
    
    # Override alignment parameters if options are given
    if options.beats_per_beat is not None:
        alignment.midi_beats_per_beat = options.beats_per_beat
    if options.sequence_start is not None:
        alignment.sequence_start = options.sequence_start
    if options.repeats is not None:
        repeats = []
        try:
            for string_triple in options.repeats.split(":"):
                start,end,count = string_triple.split(",")
                start,end,count = int(start), int(end), int(count)
                repeats.append((start,end,count))
        except:
            print "Error parsing repeat spans:"
            raise
        alignment.repeat_spans = repeats
    
    alignment.align(seq, mid, lyrics=options.lyrics)
    
    write_midifile(mid, outfile)
开发者ID:johndpope,项目名称:jazzparser,代码行数:53,代码来源:midialign.py


示例19: musicToMidi

def musicToMidi(filename, music):
    """
    musicToMidi takes a filename (which must end in ".mid") and a music structure and writes
    a MIDI file.
    :param filename:
    :param music:
    :return:
    """
    checkMidiCompatible(music) # are the volumes and pitches within 0-127?
    e = musicToMEvents(music) # convert to MEvents
    p = mEventsToPattern(e) # convert to a pythonmidi Pattern
    midi.write_midifile(filename, p) # write the MIDI file
开发者ID:donya,项目名称:PythonKulitta,代码行数:12,代码来源:PythonEuterpea.py


示例20: write_file

def write_file(name, results):
    """
    Takes a list of all notes generated per track and writes it to file
    """
    results = zip(*list(results))

    for i, result in enumerate(results):
        fpath = os.path.join(SAMPLES_DIR, name + '_' + str(i) + '.mid')
        print('Writing file', fpath)
        os.makedirs(os.path.dirname(fpath), exist_ok=True)
        mf = midi_encode(unclamp_midi(result))
        midi.write_midifile(fpath, mf)
开发者ID:wushuartgaro,项目名称:MusicAIComposer,代码行数:12,代码来源:generate.py



注:本文中的midi.write_midifile函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.midiread函数代码示例发布时间:2022-05-27
下一篇:
Python midi.read_midifile函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap