当前位置: 首页 > news >正文

用Python做有趣的AI项目 6:AI音乐生成器(LSTM Melody Generator)

🎵 项目名称:AI音乐生成器(LSTM Melody Generator)

🧠 项目简介

这个项目的目标是:用 AI 来自动生成简单的旋律(MIDI格式),类似于基础的钢琴曲、背景音乐片段。

我们使用一个 LSTM(长短期记忆网络)模型,它能学习并预测音符的序列结构,实现自动作曲。

🔧 技术栈

技术 用途
Python 编程语言
TensorFlow / Keras 构建神经网络
music21 分析、处理和播放 MIDI 音乐
Streamlit 构建图形界面(可视化生成结果)
🎹 音乐格式说明
我们使用的是 MIDI 格式(.mid 文件),它记录的是音符序列而不是录音,适合用于训练模型和自动生成旋律。

✅ 项目流程

📥 Step 1:数据准备(音乐序列)
读取一个或多个 .mid 文件,并用 music21 将其转为音符/和弦的序列,然后用于训练。

⚙️ Step 2:模型训练(LSTM)
用 LSTM 模型来学习音符之间的关系,通过预测下一个音符生成完整旋律。

🧪 Step 3:生成旋律(Predict)
给一个起始片段,自动预测接下来的 50~200 个音符。

💾 Step 4:保存为 MIDI 文件
把生成的音符序列转换成音乐文件(.mid)并保存或播放。

📄 项目代码(打包为 Python 文件)
保存为:music_generator.py

pythonimport numpy as np
from music21 import converter, instrument, note, chord, stream
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
import glob
import pickle

Step 1: 提取音符

def get_notes():notes = []for file in glob.glob("midi_songs/*.mid"):midi = converter.parse(file)parts = instrument.partitionByInstrument(midi)notes_to_parse = parts.parts[0].recurse() if parts else midi.flat.notesfor element in notes_to_parse:if isinstance(element, note.Note):notes.append(str(element.pitch))elif isinstance(element, chord.Chord):notes.append('.'.join(str(n) for n in element.normalOrder))with open("data/notes.pkl", "wb") as f:pickle.dump(notes, f)return notes

Step 2: 准备训练序列

def prepare_sequences(notes, sequence_length=100):pitchnames = sorted(set(notes))note_to_int = {note: i for i, note in enumerate(pitchnames)}network_input = []network_output = []for i in range(len(notes) - sequence_length):seq_in = notes[i:i + sequence_length]seq_out = notes[i + sequence_length]network_input.append([note_to_int[n] for n in seq_in])network_output.append(note_to_int[seq_out])n_patterns = len(network_input)network_input = np.reshape(network_input, (n_patterns, sequence_length, 1)) / float(len(pitchnames))network_output = np.eye(len(pitchnames))[network_output]return network_input, network_output, note_to_int, pitchnames

Step 3: 创建模型

def create_network(network_input, output_dim):model = Sequential()model.add(LSTM(256, input_shape=(network_input.shape[1], network_input.shape[2]), return_sequences=True))model.add(Dropout(0.3))model.add(LSTM(256))model.add(Dense(128, activation='relu'))model.add(Dropout(0.3))model.add(Dense(output_dim, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam')return model

Step 4: 生成音符

def generate_notes(model, network_input, pitchnames, note_to_int, num_notes=100):int_to_note = {num: note for note, num in note_to_int.items()}start = np.random.randint(0, len(network_input) - 1)pattern = network_input[start]prediction_output = []for note_index in range(num_notes):prediction_input = np.reshape(pattern, (1, len(pattern), 1))prediction = model.predict(prediction_input, verbose=0)[0]index = np.argmax(prediction)result = int_to_note[index]prediction_output.append(result)pattern = np.append(pattern, [[index / float(len(pitchnames))]], axis=0)pattern = pattern[1:]return prediction_output

Step 5: 将音符输出为 MIDI 文件

def create_midi(prediction_output, filename="output.mid"):offset = 0output_notes = []for pattern in prediction_output:if "." in pattern or pattern.isdigit():notes_in_chord = pattern.split(".")notes = [note.Note(int(n)) for n in notes_in_chord]chord_notes = chord.Chord(notes)chord_notes.offset = offsetoutput_notes.append(chord_notes)else:new_note = note.Note(pattern)new_note.offset = offsetoutput_notes.append(new_note)offset += 0.5midi_stream = stream.Stream(output_notes)midi_stream.write('midi', fp=filename)

▶️ 使用说明

下载一些 MIDI 文件放入 midi_songs/ 文件夹

创建 data/ 文件夹用于保存训练数据

执行以下代码:

pythonnotes = get_notes()
network_input, network_output, note_to_int, pitchnames = prepare_sequences(notes)
model = create_network(network_input, output_dim=len(pitchnames))
model.fit(network_input, network_output, epochs=20, batch_size=64)

生成音乐

prediction = generate_notes(model, network_input, pitchnames, note_to_int, num_notes=200)
create_midi(prediction)

相关文章:

  • 界面控件DevExpress WPF v25.1预览 - AI功能增强(语义搜索)
  • cas面试题
  • zynq 7010 PS 串口打印
  • 【ESP32】st7735s + LVGL移植
  • nginx代理websocket时ws遇到仅支持域名访问的处理
  • 整合性安全总结(ISS)早期规划
  • 通配符SSL证书:保护多个子域名的安全解决方案
  • 10.Excel:快速定位目标值
  • 第二节:文件系统
  • OpenCV VC编译版本
  • 《数据结构之美--二叉树》
  • 使用OpenCV和dlib库进行人脸关键点定位
  • TDR阻抗会爬坡? 别担心,不是你的错,你只是不够了解TDR!
  • opendds的配置
  • WebRtc08:WebRtc信令服务器实现
  • 牟乃夏《ArcGIS Engine 地理信息系统开发教程》学习笔记 4-空间分析与高级功能开发
  • 在单片机编程中充分使用抽象工厂模式,确保对象创建的限制,多使用抽象接口避免多变具体实现类
  • 算法笔记.染色法判断二分图
  • Python爬虫(9)Python数据存储实战:基于pymysql的MySQL数据库操作详解
  • Unity C#入门到实战: 启动你的第一个2D游戏项目(平台跳跃/俯视角射击) - 规划与核心玩法实现 (Day 40)
  • 商务部新闻发言人就波音公司飞回拟交付飞机答记者问
  • 我国将开展市场准入壁垒清理整治行动
  • 在循环往复的拍摄中,重新发现世界
  • 2025上海车展的三个关键词:辅助驾驶、性价比,AI生态
  • 俄军方:已完成库尔斯克地区全面控制行动
  • 罗马教皇方济各葬礼在梵蒂冈举行