本文整理汇总了Python中midiutil.MidiFile.MIDIFile.addTrackName方法的典型用法代码示例。如果您正苦于以下问题:Python MIDIFile.addTrackName方法的具体用法?Python MIDIFile.addTrackName怎么用?Python MIDIFile.addTrackName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类midiutil.MidiFile.MIDIFile
的用法示例。
在下文中一共展示了MIDIFile.addTrackName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: play
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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)
示例2: MidiFileCreator
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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: make_song_file
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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()
示例4: matrix_to_midi
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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)
示例5: FileOutput
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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)
示例6: midFile
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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
示例7: export
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [as 别名]
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)
示例8: playMIDI
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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
示例9: test_one_text_column
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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)
示例10: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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()
示例11: saveMIDI
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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()
示例12: write_midi_file
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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)
示例13: render
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [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
示例14: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [as 别名]
class Midi:
"""Musique midi"""
def __init__(self, partition, titre, tempo):
# Définition des paramètres MIDI.
piste = 0
temps = 0
self.tempo = tempo / 2
self.sortiemidi = MIDIFile(1, file_format=1)
# Nom de la piste.
self.sortiemidi.addTrackName(piste, temps, sansaccents(titre))
# Tempo.
self.sortiemidi.addTempo(piste, temps, self.tempo)
# Instrument (74 : flûte).
self.sortiemidi.addProgramChange(piste, 0, temps, 74)
self.traiter_partition(partition, piste, temps)
def traiter_partition(self, partition, piste, temps):
"""Création des évènements MIDI"""
transposition = partition.transposition
channel = 0
volume = 127
for mot in partition:
for i, syllabe in enumerate(mot):
syl = str(syllabe)
if i + 1 < len(mot):
syl = syl + '-'
for j, note in enumerate(
notes for notes in syllabe.musique
if isinstance(notes, Note)
):
pitch = note.hauteur + transposition
duree = int(note.duree)
self.sortiemidi.addTempo(
piste, temps, (self.tempo * duree / note.duree)
)
self.sortiemidi.addNote(
piste,
channel,
pitch,
temps,
duree / 2,
volume
)
if j == 0:
self.sortiemidi.addText(
piste,
temps,
syl
)
temps += duree / 2
def ecrire(self, chemin):
"""Écriture effective du fichier MIDI"""
with (
open(sys.stdout.fileno(), 'wb')
if chemin == '-'
else open(chemin, 'wb')
) as sortie:
self.sortiemidi.writeFile(sortie)
示例15: run
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addTrackName [as 别名]
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()