Install
pip install numpy
pip install mido
pip install soundfile
pip install streamlit
Code
import numpy as npimport soundfile as sfimport streamlit as stfrom mido import Message, MidiFile, MidiTrackimport randomdef 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 Scaleelif style == "Bright":notes = [72, 74, 76, 77, 79, 81, 83, 84] # Higher octave C Major Scaleelif style == "Mysterious":notes = [60, 63, 65, 68, 70, 73, 75, 78] # Suspenseful scaleelse:notes = [60, 62, 64, 67, 69] # Default to C Pentatonic Scaletotal_ticks = 0ticks_per_note = 480while 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_notemid.save(midi_filename)return midi_filename# Streamlit Appdef main():st.title("Random Music Generator")# User inputsstyle = 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 linkwith 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