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

Python MidiFile.MIDIFile类代码示例

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

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



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


示例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()
开发者ID:jackdreilly,项目名称:isobar,代码行数:34,代码来源:midifile.py


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


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


示例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()
开发者ID:howthebodyworks,项目名称:isobar,代码行数:31,代码来源:midifile.py


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


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


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


示例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)
开发者ID:edwardgroberski,项目名称:CSC-394,代码行数:35,代码来源:sound.py


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


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


示例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()    
开发者ID:justinsalamon,项目名称:upf-scripts,代码行数:29,代码来源:audio_to_midi_melody.py


示例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
开发者ID:paulbalaji,项目名称:cosmic_ray_project,代码行数:35,代码来源:surya.MIDI.py


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


示例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
开发者ID:sagnew,项目名称:Vireo,代码行数:28,代码来源:composer.py


示例16: create_midi

def create_midi(tempo, data):
  print 'Converting to MIDI.'
  song = MIDIFile(1)
  song.addTempo(0, 0, tempo)

  grouped = [(note, sum(1 for i in g)) for note, g in groupby(data)]
  time = 0
  for note, duration in grouped:
    add_note(song, 0, note, time, duration)
    time += duration
  return song
开发者ID:kdebowski,项目名称:img2midi,代码行数:11,代码来源:img2midi.py


示例17: testSysEx

 def testSysEx(self):
     MyMIDI = MIDIFile(1)
     MyMIDI.addSysEx(0, 0, 0, struct.pack(">B", 0x01))
     MyMIDI.close()
     self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, "SysEx")
     self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[0])[0], 0x00)
     self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[1])[0], 0xF0)
     self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[2])[0], 3)
     self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[3])[0], 0x00)
     self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[4])[0], 0x01)
     self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[5])[0], 0xF7)
开发者ID:felipebetancur,项目名称:sonify-1,代码行数:11,代码来源:miditest.py


示例18: reset_track

 def reset_track(self):
     if self.track:
         del self.track
         self.track = None
     track = MIDIFile(1)
     track.addTrackName(0, 0, "beatfruit-recording") # FIXME: Use a nicer name, template it and include timestamp???
     track.addTempo(0, 0, 120) # FIXME: Will impliment tempo changes later!
     self.track = track
     self.events = []
     self.chans = {}
     self.last_timestamp = None
     self.base_time = None
开发者ID:craiggowing,项目名称:beatfruit,代码行数:12,代码来源:beatfruit-poller.py


示例19: run

    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()
开发者ID:kathrine0,项目名称:TIRTProject,代码行数:57,代码来源:service.py


示例20: main

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)
开发者ID:alldne,项目名称:midigen,代码行数:13,代码来源:midigen.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python mido.get_output_names函数代码示例发布时间:2022-05-27
下一篇:
Python base._Unit函数代码示例发布时间: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