本文整理汇总了Python中midiutil.MidiFile.MIDIFile.addProgramChange方法的典型用法代码示例。如果您正苦于以下问题:Python MIDIFile.addProgramChange方法的具体用法?Python MIDIFile.addProgramChange怎么用?Python MIDIFile.addProgramChange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类midiutil.MidiFile.MIDIFile
的用法示例。
在下文中一共展示了MIDIFile.addProgramChange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: savefile
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [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"
示例2: FileOutput
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [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)
示例3: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [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)
示例4: __init__
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
class midiFile:
"""
Allows MIDI files to be gradually built up.
On creation, a MIDI file track is created, and notes are added through calls
to addNote.
The file can be saved through a call to writeFile.
More information on the library being used at:
http://www.emergentmusics.org/mididutil-class-reference
"""
def __init__(self, trackName, maxPackageDepth, bpm):
self.state = MIDIFile(1) #Number of tracks.
self.time = 0
self.track = 0
self.state.addTempo(self.track,self.time,bpm)
self.maxPackageDepth = maxPackageDepth
self.minPitch = 0
self.maxPitch = 127
def setPitchRange(self, min, max):
""" Set the range (somewhere between 0-127) that will be used in assigning pitch to notes,
which is based on package depth.
"""
self.minPitch = min
self.maxPitch = max
def addNote(self, depth, instrument, duration):
""" Adds a new note to the MIDI file.
Increments the time by 1 on addition of every note.
depth: Package structure depth. Used to determine the pitch of the note.
instrument: Number from 0-127 (see: http://en.wikipedia.org/wiki/General_MIDI#Program_change_events)
duration: Number of beats note should be played over.
"""
channel = 0
pitch = getPitch(depth, self.maxPackageDepth, self.minPitch, self.maxPitch)
volume = 127
logging.info("Adding note, with instrument {0}, pitch {1}, duration {2}".format(instrument, pitch, duration))
self.state.addProgramChange(self.track,channel, self.time, instrument)
self.state.addNote(0,channel,pitch,self.time,duration,volume)
self.time+=1
def writeFile(self, savePath):
""" Write the current state of the MIDI file to disk.
savePath: Name+Path of the MIDI file to be saved.
"""
binfile = open(savePath, 'wb')
self.state.writeFile(binfile)
binfile.close()
示例5: write_midi
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
def write_midi(filename, sequence):
filename = "markov/"+filename
midi = MIDIFile(1)
track = 0
start_time = 0
midi.addTrackName(track, start_time, filename[:-4])
tempo = random.randrange(360, 480)
midi.addTempo(track, start_time, tempo)
midi.addProgramChange(0, 0, 0, 1)
for i in range(len(sequence)):
note = sequence[i]
midi.addNote(track, 0, note.pitch, note.time, note.duration, note.volume)
f = open(filename, 'w')
midi.writeFile(f)
f.close()
示例6: handle_score
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
def handle_score(score):
parts = score.findall('part-list/score-part')
midiparts = []
for part in parts:
actualpart = score.find('part[@id="%s"]' % part.get('id'))
tuning = handle_tuning(actualpart)
trackname = gettext(part.find('part-name'))
midipart = MIDIFile(1)
midipart.addTrackName(0, 0, trackname)
midipart.name = trackname
for channel, _ in enumerate(tuning):
midipart.addProgramChange(0, channel, 0, getint(part.find('.//midi-program')))
midipart.addTempo(0, 0, 120)
handle_measures(midipart, actualpart, tuning)
midiparts.append(midipart)
return midiparts
示例7: main
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
def main():
prefix = os.getcwd() + '\\samples\\'
parser = argparse.ArgumentParser()
parser.add_argument('filename', help='the name of the image file')
args = parser.parse_args()
filename = args.filename
while filename != 'quit()':
try:
filename = prefix + filename
pixels = get_pixels(filename)
pixels88 = normalize_height(pixels)
colors = get_colors(pixels88)
print colors
if len(colors) > 15:
raise ColorException()
break
except IOError:
print 'File not found. Please enter a valid filename.'
filename = raw_input(
'Please enter the name of your image file (or type \'quit()\' to quit):\n')
except ColorException:
print 'This image has too many colors.'
filename = raw_input(
'Please enter the name of your image file (or type \'quit()\' to quit):\n')
if filename == 'quit()':
return
midi = MIDIFile(len(colors))
track = 0
for color in colors:
instrument = int((color[0]*100+color[1]*10+color[2]) / (28305/127))
midi.addProgramChange(track, track, 0, instrument)
colors[color] = create_masterlist(color, pixels88)
convert_to_music(midi, colors[color], track, tempo=240)
track += 1
#print `color` + ': ' + `instrument`
# filename = 'beautiful_' + filename
filename = filename.split('.')[0]
binfile = open(filename + ".mid", 'wb')
midi.writeFile(binfile)
binfile.close() # no idea if this is necessary or not
示例8: generate
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
def generate(n, program, suffix):
MyMIDI = MIDIFile(2)
track = 0
time = 0
MyMIDI.addTrackName(track,time,"Test")
MyMIDI.addTempo(track,time,30)
track = 0
channel = 0
time = 0
duration = 1.5
volume = 100
MyMIDI.addProgramChange(track, channel, 0, program)
MyMIDI.addNote(track,channel, plist[n], 0,duration,volume)
binfile = open("output.mid", 'wb')
MyMIDI.writeFile(binfile)
binfile.close()
os.system("fluidsynth /usr/share/sounds/sf2/FluidR3_GM.sf2 output.mid -F output.wav --sample-rate 1000")
os.system("lame -V 7 output.wav sound%d%s.mp3" % (n, suffix))
os.system("rm output.mid")
os.system("rm output.wav")
示例9: savefile
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [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):
pad_active = False
list_length = len(pad_records["pad{0}".format(i+1)])
MyMIDI.addProgramChange(0, i, 0, instrument[i]) # set channel instrument
for j in range(0, list_length):
velocity = pad_records["pad{0}".format(i+1)][j]/8
if not pad_active and (velocity > 0):
MyMIDI.addNote(0, i, 60, 0, list_length-j, velocity) # add note if velocity > 0 and pad not on
pad_active = True
elif pad_active:
MyMIDI.addControllerEvent(0, i, j, 0x07, velocity) # change volume
if velocity == 0:
pad_active = False
filename = self.browse_filepath.get() + "/" + self.saveFileName.get()
try:
binfile = open(filename, 'wb')
MyMIDI.writeFile(binfile)
binfile.close()
# print "saved"
tkMessageBox.showinfo(
" ",
"Saved MIDI file"
)
except:
tkMessageBox.showerror(
"Error",
"Cannot save MIDI file"
)
示例10: init
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
def init(parent):
global sp_midi, chord_count, bass_count, melody_count, drums_count
chord_count = 0
bass_count = 0
melody_count = 0
drums_count = 0
sp_midi = MIDIFile(5)
time = 0
sp_midi.addTrackName(mixer.channels["drums"], time, "Drums")
sp_midi.addProgramChange(mixer.channels["drums"], 10, 0, 118)
sp_midi.addTrackName(mixer.channels["bass"], time, "Bass")
sp_midi.addProgramChange(mixer.channels["bass"], mixer.channels["bass"], 0, 34)
sp_midi.addTrackName(mixer.channels["chords"], time, "Chords")
sp_midi.addProgramChange(mixer.channels["chords"], mixer.channels["chords"], 0, 88)
sp_midi.addTrackName(mixer.channels["melody"], time, "Melody")
sp_midi.addProgramChange(mixer.channels["melody"], mixer.channels["melody"], 0, 26)
print performer.bpm
sp_midi.addTempo(0,0,parent.user_tempo)
示例11: save_midi
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
def save_midi(pitches, tempo, rois, file_name):
# Create the MIDIFile Object with x tracks
MyMIDI = MIDIFile(len(rois))
for i in range(len(rois)):
# Tracks are numbered from zero. Times are measured in beats.
track = i
time = 0
# Add track name and tempo.
MyMIDI.addTrackName(track,time,str(i))
MyMIDI.addTempo(track,time,120)
MyMIDI.addProgramChange(track,0, time, rois[i]['instrument'])
pitch_roi = pitches[:,rois[i]['id']]
tempo_roi = tempo[:,rois[i]['id']]
total_time = 0
print '- - - - - - - - - - - ', rois[i]['id'], '- - - - - - - - - - - '
for j in range(len(pitches)):
channel = 0
pitch = pitch_roi[j]
# if j > 0:
# pitch -= 12
time = total_time
print j, tempo_roi[j]
duration = 0.5 / float(tempo_roi[j])
print duration
volume = 100
total_time += duration
print 'pitch:', pitch, 'time:', time, 'duration:', duration, 'tempo:', tempo_roi[j]
#set volume. the solo is always higher
if rois[i]['solo']:
if tempo_roi[j] ==1:
volume = 100
elif tempo_roi[j] == 2:
volume = 80
elif tempo_roi[j] == 4:
volume = 75
else:
volume = 50
else:
if tempo_roi[j] ==1:
volume = 70
elif tempo_roi[j] == 2:
volume = 50
elif tempo_roi[j] == 4:
volume = 45
else:
volume = 20
# Now add the note.
MyMIDI.addNote(track,channel,pitch,time,duration, volume)
# And write it to disk.
binfile = open(file_name, 'wb')
MyMIDI.writeFile(binfile)
binfile.close()
print 'file', file_name, 'saved.'
示例12: mark
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
def mark():
############################################################################
# Setup Constants
############################################################################
RED_CHANNEL = 0
GREEN_CHANNEL = 1
BLUE_CHANNEL = 2
if args.channels is None:
CHANNELS = [RED_CHANNEL,GREEN_CHANNEL,BLUE_CHANNEL]
else:
CHANNEL_CODES = {'r': RED_CHANNEL, 'g': GREEN_CHANNEL, 'b': BLUE_CHANNEL}
CHANNELS = [CHANNEL_CODES[code] for code in args.channels]
# # CHANNELS = [RED_CHANNEL]
# CHANNELS = [BLUE_CHANNEL]
# # CHANNELS = [GREEN_CHANNEL]
ROOT_NOTE = 60
MIDI_MIN = 24
MIDI_MAX = 108
RANGE = MIDI_MAX - MIDI_MIN
REST_CHANCE = 0.1
############################################################################
# Image data setup
############################################################################
# Open the image file and read the RGB pixel values into an array
im = Image.open(args.input, 'r')
width, height = im.size
pixel_values = list(im.getdata())
pixel_values = pixel_values[:1000]
############################################################################
# Setup MIDI Jawns
############################################################################
# Create the MIDIFile Object
MyMIDI = MIDIFile(1)
# Add track name and tempo
track = 0
time = 0.0
MyMIDI.addTempo(track,time, 113)
MyMIDI.addTrackName(track,time,"Music Jawns")
# RED: Chromatic Procussion
MyMIDI.addProgramChange(track,RED_CHANNEL,time, 10)
# GREEN: Brass
MyMIDI.addProgramChange(track,GREEN_CHANNEL,time, 60)
# BLUE: Brass
MyMIDI.addProgramChange(track,BLUE_CHANNEL,time, 1)
############################################################################
# Calculate the things!
############################################################################
# Initialize our running RGB data values
prevs = [0,0,0] # Previous R,G, and B values
prev_lengths = [0,0,0] # Number of previous jawns at those values
values = [[],[],[]] # When a new value is found, the old value and the count get added here
# Calculate the running sums for R/G/B
for pixel in pixel_values:
for channel in CHANNELS:
dis_pixel = pixel[channel] % RANGE
if prevs[channel] == dis_pixel:
# If this pixel value for the color is equal to
# the last color, increment the count
prev_lengths[channel] += 1
else:
# Otherwise, store the conut and reset the value
store = (prevs[channel],prev_lengths[channel])
values[channel].append(store)
prevs[channel] = dis_pixel
prev_lengths[channel] = 0
# Remove timeless jawns
for channel in CHANNELS:
values[channel] = filter(lambda (value,count): count > 0, values[channel])
values_short = [l[:10] for l in values]
print values_short
# Add a note. addNote expects the following information:
channel = RED_CHANNEL
start_pitch = ROOT_NOTE
volume = 100
for channel in CHANNELS:
time = 0.0
# Get an iterator and skip the first val
iterator = iter(values[channel])
# We change these on each loop
#.........这里部分代码省略.........
示例13: MIDIFile
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
'''Generates a MIDI file with 12 random notes in C major, using the midiutil module. The instrument is also picked randomly. The result is then played with the sound.MIDIPlayer class.
If nothing happens, make sure that your device isn't muted.
'''
from midiutil.MidiFile import MIDIFile
from random import choice, randint
import sound
# Configure a MIDI file with one track:
midi = MIDIFile(1)
midi.addTempo(0, 0, 180)
# Select a random instrument:
program = randint(0, 255)
midi.addProgramChange(0, 0, 0, program)
# Generate some random notes:
duration = 1
c_major = [60, 62, 64, 65, 67, 69, 71]
for t in range(12):
pitch = choice(c_major)
# track, channel, pitch, time, duration, volume
midi.addNote(0, 0, pitch, t * duration, duration, 100)
# Write output file:
with open('output.mid', 'w') as f:
midi.writeFile(f)
# Play the result:
player = sound.MIDIPlayer('output.mid')
player.play()
示例14: MIDIFile
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
x=(math.log(50))/72
z=(math.exp(10))/72
testmusic =wave.open(infile_loc_str,"rb")
music_params = testmusic.getparams()
nchannels,sampwidth,framerate,nframes = music_params[:4]
MyMIDI = MIDIFile(1,True)
# Tracks are numbered from zero. Times are measured in beats.
track = 0
time = 0
instrument = 1
# Add track name and tempo.
MyMIDI.addTrackName(track,time,"Sample Track")
MyMIDI.addTempo(track,time,120)
MyMIDI.addProgramChange(track,0,time,instrument)
str_data = testmusic.readframes(nframes)
testmusic.close()
wave_data = np.fromstring(str_data,dtype=np.short)
wave_data.shape = -1,2
wave_data = wave_data.T
wave_datam = wave_data[0]
nengliang = [0]*60
lengthofmusic = len(wave_data[0])
totaltimes = lengthofmusic
time_range = 441
times = totaltimes//time_range
tmp_array = [0]* times
tmp_array2 = [0]* times
示例15: MidiWorld
# 需要导入模块: from midiutil.MidiFile import MIDIFile [as 别名]
# 或者: from midiutil.MidiFile.MIDIFile import addProgramChange [as 别名]
class MidiWorld():
"""
" Define MIDI class
"
" 1. read numbered notation file, the notation file should follow the format shown below
" 2. write MIDI file
"""
def __init__(self, note_file):
self.volume = 100
self.channel = 0
self.note_file = note_file
self.set_note_list()
self.set_track_info()
#===== Initiate MIDI file object with n_track tracks =====#
self.mf = MIDIFile(self.n_track)
# mf.addTrackName(track, time, "Sample Track")
def set_note_list(self):
#===== Get note list from the notation file =====#
with open(self.note_file) as nf:
note_str = nf.read().replace('\n', ' ')
self.note_list = re.split('\s+', note_str)
def set_track_info(self):
#===== Set number of tracks and their time =====#
## number of tracks or channels, here we set the two numbers the same
self.n_track = int(self.note_list[0])
## set time for each track
self.track_time = [0]*self.n_track
## set track program
self.program = [int(x) for x in self.note_list[1:self.n_track+1]]
#===== Get tracks, the track section is contained within {} =====#
## Get track sections
self.ltc_ind = [i for i, x in enumerate(self.note_list) if x == '{']
self.rtc_ind = [i for i, x in enumerate(self.note_list) if x == '}']
if len(self.ltc_ind) != len(self.rtc_ind):
print '{ and } should be pair matched.'
sys.exit()
## Get tracks
self.track = [[] for x in range(self.n_track)]
for lind, rind in zip(self.ltc_ind, self.rtc_ind):
track_number = int(self.note_list[lind-1])
self.track[track_number] += self.note_list[lind+1:rind]
## Get the total number of track sections
# self.n_track_section = len(self.ltc_ind)
## Get every track number from the track sections,
## len(track_number_list) = n_track
# self.track_number_list = list()
# for i in range(self.n_track_section):
# self.track_number_list.append(int(self.note_list[self.ltc_ind[i]-2]))
def write_track(self, track_number):
"""
" write to track and channel
"""
#===== Get the track list =====#
track = self.track[track_number]
channel_number = track_number
#===== Set program (instrument) for the channel =====#
self.mf.addProgramChange(track_number, channel_number, self.track_time[track_number], self.program[track_number])
#===== Find every piece contained by paired [] =====#
lp_ind = [i for i, x in enumerate(track) if x == '[']
rp_ind = [i for i, x in enumerate(track) if x == ']']
if len(lp_ind) != len(rp_ind):
print '[ and ] should be pair matched.'
sys.exit()
for p in range(len(lp_ind)):
#===== Tempo and major symbol are before the '[' =====#
tempo = int(track[lp_ind[p]-2])
self.mf.addTempo(track_number, self.track_time[track_number], tempo)
major = track[lp_ind[p]-1]
major_pitch = note_to_pitch(major)
#===== Resolve every note =====#
for s in track[lp_ind[p]+1:rp_ind[p]]:
pitch, beat = numnote_resolve(s)
if pitch != 999: # if it is not break note (0)
self.mf.addNote(track_number, channel_number,
major_pitch+pitch, self.track_time[track_number], beat, self.volume)
self.track_time[track_number] += beat
def write_midifile(self, output_midi_file):
#===== write to each channel =====#
for itc in range(self.n_track):
print 'itc:', itc
self.write_track(itc)
#.........这里部分代码省略.........