用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

cpp 复制代码
python

import 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: 提取音符

cpp 复制代码
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.notes

        for 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: 准备训练序列

cpp 复制代码
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: 创建模型

cpp 复制代码
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: 生成音符

cpp 复制代码
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 文件

cpp 复制代码
def create_midi(prediction_output, filename="output.mid"):
    offset = 0
    output_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 = offset
            output_notes.append(chord_notes)
        else:
            new_note = note.Note(pattern)
            new_note.offset = offset
            output_notes.append(new_note)
        offset += 0.5

    midi_stream = stream.Stream(output_notes)
    midi_stream.write('midi', fp=filename)

▶️ 使用说明

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

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

执行以下代码:

cpp 复制代码
python

notes = 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)

生成音乐

cpp 复制代码
prediction = generate_notes(model, network_input, pitchnames, note_to_int, num_notes=200)
create_midi(prediction)
相关推荐
移远通信几秒前
从机械应答到深度交互,移远通信如何让机器人“灵魂觉醒”?
人工智能
小革36010 分钟前
JAVA批量发送邮件(含excel内容)
开发语言·python·excel
阿梦Anmory11 分钟前
[解决conda创建新的虚拟环境没用python的问题]
开发语言·python·conda
L_cl12 分钟前
【NLP 77、Python环境管理工具之conda】
python·自然语言处理·conda
心扬19 分钟前
python容器
开发语言·python
钰爱&34 分钟前
【OpenCV】基本数据类型及常见图像模式
人工智能·opencv·计算机视觉
Jamence42 分钟前
多模态大语言模型arxiv论文略读(八十九)
论文阅读·人工智能·语言模型·自然语言处理·论文笔记
AI technophile1 小时前
OpenCV计算机视觉实战(7)——色彩空间详解
人工智能·opencv·计算机视觉
绝顶大聪明1 小时前
[欠拟合过拟合]机器学习-part10
人工智能·机器学习
芷栀夏1 小时前
Dify大语言模型应用开发环境搭建:打造个性化本地LLM应用开发工作台
人工智能·语言模型·自然语言处理