Search This Blog

2025/01/17

music_generator by Python

Install

pip install numpy

pip install mido

pip install soundfile

pip install streamlit


Code
import numpy as np
import soundfile as sf
import streamlit as st
from mido import Message, MidiFile, MidiTrack
import random

def create_random_melody(style, instrument, duration=180):
    """
    Generates a random melody and saves it as a MIDI file.

    Args:
        style (str): The selected music style ('Calm', 'Bright', 'Mysterious').
        instrument (str): The selected instrument ('Piano', 'Violin', 'Flute', etc.).
        duration (int): Duration of the melody in seconds.

    Returns:
        str: Filename of the generated MIDI file.
    """
    midi_filename = f"{style}_{instrument}_music.mid"
    mid = MidiFile()
    track = MidiTrack()
    mid.tracks.append(track)

    if style == "Calm":
        notes = [60, 62, 64, 65, 67, 69, 71, 72]  # C Major Scale
    elif style == "Bright":
        notes = [72, 74, 76, 77, 79, 81, 83, 84]  # Higher octave C Major Scale
    elif style == "Mysterious":
        notes = [60, 63, 65, 68, 70, 73, 75, 78]  # Suspenseful scale
    else:
        notes = [60, 62, 64, 67, 69]  # Default to C Pentatonic Scale

    total_ticks = 0
    ticks_per_note = 480

    while total_ticks < duration * 480:
        note = random.choice(notes)
        velocity = random.randint(50, 100)
        track.append(Message('note_on', note=note, velocity=velocity, time=0))
        track.append(Message('note_off', note=note, velocity=velocity, time=ticks_per_note))
        total_ticks += ticks_per_note

    mid.save(midi_filename)
    return midi_filename

# Streamlit App
def main():
    st.title("Random Music Generator")

    # User inputs
    style = st.selectbox("Choose a music style:", ["Calm", "Bright", "Mysterious"])
    instrument = st.selectbox("Choose an instrument:", ["Piano", "Violin", "Flute", "Guitar"])
    duration = st.slider("Select duration (seconds):", min_value=30, max_value=180, step=30, value=90)
    file_format = st.selectbox("Select file format:", ["MIDI"])

    if st.button("Generate Music"):
        st.write(f"Generating {style} music with {instrument} for {duration} seconds...")

        if file_format == "MIDI":
            midi_filename = create_random_melody(style, instrument, duration)
            st.success("MIDI file generated successfully!")

            # Provide MIDI download link
            with open(midi_filename, "rb") as midi_file:
                st.download_button(
                    label="Download MIDI File",
                    data=midi_file,
                    file_name=midi_filename,
                    mime="audio/midi"
                )

if __name__ == "__main__":
    main()


RUN

streamlit run music_generator.py