当前位置: 首页>>代码示例>>Python>>正文


Python MIDIFile.addNote方法代码示例

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


在下文中一共展示了MIDIFile.addNote方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: MidiFileCreator

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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"
开发者ID:biggerfisch,项目名称:mhacks-fall13,代码行数:34,代码来源:chord_generator.py

示例2: __init__

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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()
开发者ID:jackdreilly,项目名称:isobar,代码行数:36,代码来源:midifile.py

示例3: write_midi_file

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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)
开发者ID:JoshRosen,项目名称:tabtomidi,代码行数:28,代码来源:drumtabs.py

示例4: savefile

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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"
开发者ID:lorrainechoi,项目名称:Pressure_Recorder,代码行数:28,代码来源:gui_windows.py

示例5: __init__

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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()
开发者ID:gurk,项目名称:isobar,代码行数:30,代码来源:midifile.py

示例6: __init__

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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()
开发者ID:ideoforms,项目名称:isobar,代码行数:32,代码来源:midifile.py

示例7: __init__

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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()
开发者ID:mnvl,项目名称:solfeggio,代码行数:27,代码来源:solfeggio.py

示例8: matrix_to_midi

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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)
开发者ID:Nospoko,项目名称:blompf,代码行数:29,代码来源:midi.py

示例9: play

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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)
开发者ID:edwardgroberski,项目名称:CSC-394,代码行数:37,代码来源:sound.py

示例10: midFile

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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
开发者ID:sagnew,项目名称:Vireo,代码行数:30,代码来源:composer.py

示例11: test_one_text_column

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [as 别名]
def test_one_text_column():
    '''
    A data frame with a single integer column
    should be converted correctly.
    '''
    expected = MIDIFile(1)
    expected.addTrackName(0,0,"vocals")
    expected.addTempo(0,0,120)
    for time,note in enumerate([38, 40, 42, 43]):
        expected.addNote(0,0,note,time,1,100)

    df = pandas.DataFrame([
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'mushroom'},
        {'vocals':'mushroom'},
    ])
    observed = df_to_midi(df, bpm = 120)

    n.assert_equal(observed, expected)
开发者ID:csv,项目名称:ddpy,代码行数:27,代码来源:test_df_to_midi.py

示例12: FileOutput

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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)
开发者ID:shish,项目名称:mic2midi,代码行数:30,代码来源:outputs.py

示例13: saveMIDI

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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()    
开发者ID:justinsalamon,项目名称:upf-scripts,代码行数:31,代码来源:audio_to_midi_melody.py

示例14: convert_to_song

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [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()
开发者ID:abbasally5,项目名称:woodstocks,代码行数:36,代码来源:song.py

示例15: playMIDI

# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addNote [as 别名]
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,代码行数:37,代码来源:surya.MIDI.py


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