def gen_pieces(n): for i in range(n): note_weights = [1] * len(MusicGenerator.note_range) note_weights[0] = 1 time_weights = [1] * len(MusicGenerator.time_range) options = {} options["note_weights"] = note_weights options["time_weights"] = time_weights generator = MusicGenerator(options=options) musc = generator.tinynotation(n_bars=2000) print(musc) stream = converter.parse("tinynotation: " + musc) # stream.show("text") # stream.show("musicxml") conv_musicxml = ConverterMusicXML() scorename = 'myScoreName{:03}.xml'.format(i) filepath = './tests/' + scorename out_filepath = conv_musicxml.write(stream, 'musicxml', fp=filepath, subformats=['png'])
def generate_sheet_music(midi_file_path, filetype="pdf"): try: mf = midi.MidiFile() mf.open(str(midi_file_path)) mf.read() mf.close() print("\n\n -- Midi successfully read --- \n\n") # get stream s = midi.translate.midiFileToStream(mf) print("\n\n -- Stream successfully created --- \n\n") # write sheet music as pdf/png conv_musicxml = ConverterMusicXML() emptyDirectory(config.sheet_music_save_location) scorename = os.path.join(config.sheet_music_save_location, config.sheet_music_name) print("\n\n -- Score name: {} --- \n\n".format(scorename)) if filetype == "pdf": print("\n\n -- Filetype pdf --- \n\n") out_flepath = conv_musicxml.write(s, 'musicxml', fp=scorename, subformats=['pdf']) else: print("\n\n -- Filetype not pdf --- \n\n") out_flepath = conv_musicxml.write(s, 'musicxml', fp=scorename, subformats=['png']) return out_flepath except: print("\n\n--- Something went wrong ---\n\n") return None
def display_music(file, opusnum): s = converter.parse(f'esac/{file}', number=opusnum) s.metadata.title = '' us = environment.UserSettings() us['autoDownload'] = 'allow' us['lilypondPath'] = 'C:/Program Files (x86)/LilyPond/usr/bin/lilypond.exe' us['musescoreDirectPNGPath'] = 'C:/Program Files/MuseScore 3/bin/MuseScore3.exe' us['musicxmlPath'] = 'C:/Program Files/MuseScore 3/bin/MuseScore3.exe' filepath = r'output' conv_musicxml = ConverterMusicXML() out_filepath = conv_musicxml.write(s, 'musicxml', fp=filepath, subformats=['png']) # importing PIL #from PIL import Image #img = Image.open(filepath + '-1.png') #img.show() s.show()
def GenerateFile(filename): #CONSTANTS #./amazing_grace_female.wav confidence_threshold = 0.6 #CREPE must be at least this confident about a note's pitch for it to count tuning_freq = 440 #Root of tuning system (the default value here reflects A440) min_duration = 4 #The least number of frames in a row that must hold a pitch to register as a note #DISCARD_THRESH MUST BE AT LEAST 3 OR THE PROGRAM WILL CRASH hard-code this into the interface and it will be fine discard_thresh = 3 #"Notes" and indeterminate-frequency patches this many frames or shorter are discarded or replaced address = filename #input("Enter path of audio file\n") sr, audio = wavfile.read(address) time, frequency, confidence, activation = crepe.predict(audio, sr, viterbi=True) #Eliminate low-confidence or indeterminate-frequency estimates for i in range(frequency.size): if frequency[i] <= 0 or confidence[i] < confidence_threshold: frequency[i] = 0 #Convert frequencies to MIDI numbers midi = [] for i in range(frequency.size): if (frequency[i]) > 0: note = round(np.log2(frequency[i] / tuning_freq) * 12 + 69) midi = np.append(midi, note) else: midi = np.append(midi, 0) #The complicated part: #ironing out short pitch wobbles & vacant/uncertain-pitch deviations #by replacing their MIDI numbers with those of their neighbours # print("midi before") # print(midi) #Prep: add one extra zero to the midi array so that Pass 1 doesn't have trouble at the end of the array midi = np.append(midi, 0) #Pass 1: replace too-short tones with zeroes count = 1 for frame in range(midi.size - 1): if midi[frame] == midi[frame + 1]: count += 1 #count the number of identical pitches in a row else: if count <= discard_thresh: #if tone is too short to be counted for i in range(0, count): midi[frame - i] = 0 #kablammo count = 1 #reset counter; you now have precisely one of the same numbers in a row # print("midi after too-short-tones' replacement with zeroes but before filling in gaps with good tones") # print(midi) #Pass 2: fill in too-short patches of zeroes with the tone immediately following them count = 0 for frame in range(midi.size): if midi[frame] == 0: count += 1 #count the number of zeroes in a row else: if count <= discard_thresh: #if streak of zeros is too short to be counted if frame + discard_thresh + 1 <= midi.size: #if there are enough frames left in the midi array standard = midi[ frame + 1] #do the following frames match this one? good_trailing = True #Represents whether there is a long-enough tone after the streak of zeroes to fill it in with for i in range(frame + 2, frame + discard_thresh + 1): if midi[i] != standard: good_trailing = False break if (good_trailing): for i in range(count): midi[frame - i - 1] = standard #kablammo count = 0 #Finally, let's generate a list of MIDI notes #expressed as trios of numbers: MIDI number, start time (ms), end time (ms), length(ms) final = np.array([[0, 0, 0, 0]]) hold_freq = midi[0] start_frame = 0 for frame in range(1, midi.size): if midi[frame] != hold_freq: if hold_freq != 0: data = np.array([[ hold_freq, start_frame * 10, frame * 10, frame * 10 - start_frame * 10 ]]) final = np.concatenate([final, data], axis=0) hold_freq = midi[frame] start_frame = frame # Need to use MuseScore to show music score # Set up path to the installed env = music21.environment.Environment() # check the path #print('Environment settings:') #print('musicXML: ', env['musicxmlPath']) #print('musescore: ', env['musescoreDirectPNGPath']) env['musescoreDirectPNGPath'] = 'C:\Program Files (x86)\MuseScore 3\\bin\\MuseScore3.exe' env['musicxmlPath'] = 'C:\Program Files (x86)\MuseScore 3\\bin\\MuseScore3.exe' #print('musescore: ', env['musescoreDirectPNGPath']) #One possible way to clamp each output duration to music note duration # note_durations = np.array([1/64, 1/32, 1/16, 1/8, 1/4, 1/2, 1]) # def find_nearest(array, value): # array = np.asarray(array) # idx = (np.abs(array - value)).argmin() # return array[idx] midi_stream = music21.stream.Stream() #Initial sound is not played, so append empty sound. n = music21.note.Note(0) midi_stream.append(n) sum_time = 0 for x in final: min_length = 16 dur = x[3] dur /= 1000.0 #convert to sec dur *= min_length #clamp duration into 128th duration type dur = round(dur) n = music21.note.Note(x[0]) n.duration.quarterLength -= 1 n.duration.quarterLength += dur / min_length if n.quarterLength > 0.0: midi_stream.append(n) sum_time += dur / min_length fp = midi_stream.write('xml', fp='./Test.xml') fp = midi_stream.write('midi', fp='./Test.mid') conv_musicxml = ConverterMusicXML() out_filepath = conv_musicxml.write(midi_stream, 'musicxml', fp='./Test.xml', subformats=['png']) print("done!")
def get_img(json_input): """ :param json_input: :return the path of generated 五线谱: eg, 'static/upload/img/output_img1.jpg': """ #把json_input变成列表 lyric=[] myDuration=[] myNote=[] for i in range(len(json_input)): lyric.append(json_input[i]["lyrics"]+' &') myDuration.append(json_input[i]["duration"]+[1]) myNote.append(json_input[i]["key"]+['rest']) lyric=[i for x in lyric for i in x.split(' ')] myDuration=[i for x in myDuration for i in x] myNote=[i for x in myNote for i in x] for i in range(len(lyric)): if lyric[i]=='&': lyric[i]=' ' #把一个字的多个音分开 for i in range(len(myNote)): if len(myNote[i])>=5: if len(myNote[i])==5: lyric[i]=[lyric[i],' '] myDuration[i]=[str(float(myDuration[i])/2),str(float(myDuration[i])/2)] if len(myNote[i])==8: lyric[i]=[lyric[i],' ',' '] myDuration[i]=[str(float(myDuration[i])/3),str(float(myDuration[i])/3),str(float(myDuration[i])/3)] if len(myNote[i])==11: lyric[i]=[lyric[i],' ',' ',' '] myDuration[i]=[str(float(myDuration[i])/4),str(float(myDuration[i])/4),str(float(myDuration[i])/4),str(float(myDuration[i])/4)] else: myNote[i]=myNote[i][0:2] myNote[i] = myNote[i].split(',') flatten = lambda x: [subitem for item in x for subitem in flatten(item)] if type(x) is list else [x] lyric=flatten(lyric) myDuration=flatten(myDuration) myNote=flatten(myNote) #调整音的长度 myDuration=['0.25' if x=='0.2' else x for x in myDuration] myDuration=['0.75' if x=='0.7' else x for x in myDuration] myDuration=['1.25' if x=='1.2' else x for x in myDuration] #把myNote转化为标准音高 temp=[] pit=['c','c#','d','d#','e','f','f#','g','g#','a','a#','b'] for i in range(len(myNote)): if myNote[i] == 'rest': temp.append('rest') else: num = (int(myNote[i])-67)%12 if num in range(12): temp.append(pit[num]) for i in range(len(myNote)): if temp[i] != 'rest': myNote[i]=temp[i] + str(4+(int(myNote[i])-67)//12) #连接乐谱 m= stream.Stream() m.append(meter.TimeSignature('4/4')) for i in range(len(myNote)): if myNote[i] == 'rest': temp=note.Rest() temp.myDuration=duration.Duration(1) temp.lyric='' else: temp=note.Note(myNote[i]) temp.myDuration=duration.Duration(float(myDuration[i])) temp.lyric=lyric[i] m.append(temp) us = environment.UserSettings() us['musescoreDirectPNGPath'] = '/Applications/MuseScore 3.app/Contents/MacOS/mscore' from music21.converter.subConverters import ConverterMusicXML conv_musicxml = ConverterMusicXML() uuid_str = uuid.uuid4().hex temp_file_name = 'tmpfile_%s' % uuid_str scorename = temp_file_name + '.xml' filepath = 'static/upload/img/'+scorename out_filepath = conv_musicxml.write(m, 'musicxml', fp=filepath, subformats=['png']) return temp_file_name + '-1.png'
score.elements[0].remove(score.elements[0].elements[-1]) for num in range(1, onset): print("removing " + str(score.elements[1])) score.remove(score.elements[1]) for thisElement in score: if thisElement.offset > 0: thisElement.offset -= onset score = score[0:4] us = environment.UserSettings() us['autoDownload'] = 'allow' us['lilypondPath'] = 'C:/Program Files (x86)/LilyPond/usr/bin/lilypond.exe' us['musescoreDirectPNGPath'] = 'C:/Program Files/MuseScore 3/bin/MuseScore3.exe' us['musicxmlPath'] = 'C:/Program Files/MuseScore 3/bin/MuseScore3.exe' filepath = r'C:\Users\Alice\Documents\GitHub\battlenotes\hi' conv_musicxml = ConverterMusicXML() scorename = 'Blues_For_Alice.xml' out_filepath = conv_musicxml.write(score, 'musicxml', fp=filepath, subformats=['png']) # importing PIL from PIL import Image img = Image.open(filepath + '-1.png') img.show()
def extract_lines(pathLoad, pathSave, labelFileName): startTime = time.time() os.makedirs(pathSave, exist_ok=True) filenames = [f for f in os.listdir(pathLoad) if f.endswith('.mxl')] print("Lines extraction") errorFiles = [] with open(labelFileName, 'w') as txt: for filename, i in zip(filenames, range(len(filenames))): try: conv_musicxml = ConverterMusicXML() sheet = converter.parse(pathLoad + filename) measuresLine = [] lineToKeep = False nbImages = 0 for part in sheet.parts: measures = [ m for m in part if type(m) == music21.stream.Measure ] for measure in measures: if len([ obj for obj in measure if type(obj) == music21.layout.SystemLayout ]) != 0: if lineToKeep: sheetLine = sheet.measures( measuresLine[0], measuresLine[-1]) sheetLine = dropLyrics(sheetLine) label = labelList(sheetLine) if label is not None: error = conv_musicxml.write( sheetLine, fmt='musicxml', subformats=['png']) os.rename( error, pathSave + filename.replace('.mxl', '') + '_' + str(nbImages) + '.png') txt.write( filename.replace('.mxl', '') + '_' + str(nbImages) + '.png' + ' : ' + '||'.join([ '|'.join(m) for m in labelList(sheetLine) ]) + '\n') nbImages += 1 measuresLine = [] lineToKeep = False if len([ obj for obj in measure if type(obj) == music21.note.Note ]) != 0: lineToKeep = True measuresLine.append(measure.number) if measure == measures[-1]: if lineToKeep: sheetLine = sheet.measures( measuresLine[0], measuresLine[-1]) sheetLine = dropLyrics(sheetLine) label = labelList(sheetLine) if label is not None: error = conv_musicxml.write( sheetLine, fmt='musicxml', subformats=['png']) os.rename( error, pathSave + filename.replace('.mxl', '') + '_' + str(nbImages) + '.png') txt.write( filename.replace('.mxl', '') + '_' + str(nbImages) + '.png' + ' : ' + '||'.join([ '|'.join(m) for m in labelList(sheetLine) ]) + '\n') nbImages += 1 except: errorFiles.append(filename) print('New error') sys.stdout.write( '\r' + '{0:.2f}'.format((i + 1) * 100 / len(filenames)) + ' % | Remaining Time : ' + remainingTimeDisplay(i, len(filenames), startTime) + ' ') sys.stdout.flush() endTime = time.time() print("\nTotal time : " + str(endTime - startTime)) return errorFiles
n.pitch = pitch.Pitch(p) if not isinstance(p, int): n.pitch.convertMicrotonesToQuarterTones(inPlace=True) n.quarterLength = 4.0 print(n.pitch.alter) stream1.append(n) for i in range(len(stream1)): stream1[i].offset = 0.0 l_mod = [(l + [12])[i + 1] - (l + [12])[i] for i in range(len(l))] stream1[0].lyric = str(l_mod) title = 'quarterTone_brouillon' filepath = '/Users/manuel/Dropbox (TMG)/Thèse/Estrada/' out_filepath = conv_musicxml.write(stream1, 'musicxml', fp=filepath + title + '.XML', subformats=['png']) im = Image.open(out_filepath) # width, height = im.size # region = im.crop((130, 0, 610, height)) # region.save(out_filepath[:-6] + '.png') # os.remove(filepath + title + '.XML') # os.remove(filepath + title + '-1.png') ##################### AFFICHER UN ACCORD ########################## # conv_musicxml = ConverterMusicXML() # stream1 = stream.Stream() # l = [0,1,2,3,4,5,6,7,8] # l_mod = [(l+[12])[i+1] - (l+[12])[i] for i in range(len(l))]