环境:
python3.6
pyhton库:magenta
介绍:
基于谷歌magenta python库开发,由于训练数据集麻烦,这里使用谷歌提供在线的数据集。
该脚本先按音符生成一段示例音乐,再下载magenta提供已训练好的数据集,将生成的示例音乐按训练的数据集自动生成新的音乐追加到末尾,
合成一段新的音乐序列,生成mid文件(可用音乐播放器或python库打开)保存。
import magenta.music as mmfrom magenta.protobuf import music_pb2from magenta.models.melody_rnn import melody_rnn_sequence_generatorfrom magenta.protobuf import generator_pb2twinkle_twinkle = music_pb2.NoteSequence()# 将音符添加到序列中twinkle_twinkle.notes.add(pitch=60, start_time=0.0, end_time=0.5, velocity=80)twinkle_twinkle.notes.add(pitch=60, start_time=0.5, end_time=1.0, velocity=80)twinkle_twinkle.notes.add(pitch=67, start_time=1.0, end_time=1.5, velocity=80)twinkle_twinkle.notes.add(pitch=67, start_time=1.5, end_time=2.0, velocity=80)twinkle_twinkle.notes.add(pitch=69, start_time=2.0, end_time=2.5, velocity=80)twinkle_twinkle.notes.add(pitch=69, start_time=2.5, end_time=3.0, velocity=80)twinkle_twinkle.notes.add(pitch=67, start_time=3.0, end_time=4.0, velocity=80)twinkle_twinkle.notes.add(pitch=65, start_time=4.0, end_time=4.5, velocity=80)twinkle_twinkle.notes.add(pitch=65, start_time=4.5, end_time=5.0, velocity=80)twinkle_twinkle.notes.add(pitch=64, start_time=5.0, end_time=5.5, velocity=80)twinkle_twinkle.notes.add(pitch=64, start_time=5.5, end_time=6.0, velocity=80)twinkle_twinkle.notes.add(pitch=62, start_time=6.0, end_time=6.5, velocity=80)twinkle_twinkle.notes.add(pitch=62, start_time=6.5, end_time=7.0, velocity=80)twinkle_twinkle.notes.add(pitch=60, start_time=7.0, end_time=8.0, velocity=80)twinkle_twinkle.total_time = 8twinkle_twinkle.tempos.add(qpm=60)print('下载模型包。大概用时一分钟......')mm.notebook_utils.download_bundle('basic_rnn.mag', 'content/')bundle = mm.sequence_generator_bundle.read_bundle_file('content/basic_rnn.mag')# 初始化模型print("初始化Melody RNN ......")generator_map = melody_rnn_sequence_generator.get_generator_map()melody_rnn = generator_map['basic_rnn'](checkpoint=None, bundle=bundle)melody_rnn.initialize()print('RNN初始化完成')input_sequence = twinkle_twinklenum_steps = 128 # 将此更改为更短或更长的序列temperature = 6.0 # temperature越高,序列越随机.# 在最后一个音符结束后,将开始时间设置为下一步开始。last_end_time = (max(n.end_time for n in input_sequence.notes) if input_sequence.notes else 0)qpm = input_sequence.tempos[0].qpmseconds_per_step = 60.0 / qpm / melody_rnn.steps_per_quartertotal_seconds = num_steps * seconds_per_stepgenerator_options = generator_pb2.GeneratorOptions()generator_options.args['temperature'].float_value = temperaturegenerate_section = generator_options.generate_sections.add( start_time=last_end_time + seconds_per_step, end_time=total_seconds)# 使模型生成序列sequence = melody_rnn.generate(input_sequence, generator_options)# 将sequence生成MIDI文件,可用音乐播放器打开,或通过Python库mm.sequence_proto_to_midi_file(sequence, 'drums_sample_output.mid')