How to create music with Python

https://pythonprogramming.altervista.org/wp-content/uploads/2023/01/melody.mid
example 1

https://pythonprogramming.altervista.org/wp-content/uploads/2023/01/melody2.mid
example 2

Here is an example to create some random music with python. We will generate random notes and save it to a midi file. You can play the notes with a daw of your choice or with the pygame module. We got it into the code that follows here below, have fun.

import random
from music21 import *
import os

def genmidi():
  cwd = os.getcwd()
  os.system("E:")
  os.system(f"cd {cwd}")
  print(cwd)
  # Generate a random melody by creating a stream of notes with random pitches and durations
  melody = stream.Stream()
  for i in range(10):
    pitch = random.choice(['C', 'D', 'E', 'F', 'G', 'A', 'B'])
    duration = random.choice([1, 2, 4])
    n = note.Note(pitch, quarterLength=duration)
    melody.append(n)

  # Save the melody to a MIDI file
  path = "midi_generated/melody.mid"
  midi_file = melody.write('midi', fp=path)
  return path


def genmidi2():


  # Create a stream to hold the melody
  melody = stream.Stream()

  # Create a phrase by randomly selecting from a list of pitches
  def create_phrase():
    phrase = stream.Stream()
    pitches = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
    durations = [0.5, 1, 2]
    for i in range(8):
      pitch = random.choice(pitches)
      duration = random.choice(durations)
      n = note.Note(pitch, quarterLength=duration)
      phrase.append(n)
    return phrase

  # Add three phrases to the melody
  for i in range(3):
    phrase = create_phrase()
    melody.append(phrase)

  # Set the tempo and add a time signature
  melody.insert(0, tempo.MetronomeMark(number=120))
  melody.insert(0, meter.TimeSignature('4/4'))

  # Save the melody to a MIDI file
  path = "midi_generated/melody2.mid"
  midi_file = melody.write('midi', fp=path)
  return path


def listen_midi(midi):
  import pygame
  pygame.init()
  pygame.mixer.music.load(midi)
  pygame.mixer.music.play()
  while pygame.mixer.music.get_busy():
    pygame.time.Clock().tick(10)
  return "Music's over"


midi = genmidi()
listen_midi(midi)


Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts