AI-generated Music Composition Python, AI

👤 Sharing: AI
```python
import random
import numpy as np

# --- Parameters ---
TEMPO = 120  # Beats per minute
TIME_SIGNATURE_NUMERATOR = 4
TIME_SIGNATURE_DENOMINATOR = 4
NOTE_DURATION = 0.25  # Quarter note
NUM_BARS = 8
SCALE = ["C4", "D4", "E4", "F4", "G4", "A4", "B4"]  # C Major
REST_PROBABILITY = 0.1

# --- Helper Functions ---
def bpm_to_seconds_per_beat(bpm):
  """Converts BPM to seconds per beat."""
  return 60 / bpm

def duration_to_seconds(duration, bpm):
  """Converts note duration (in beats) to seconds."""
  return duration * bpm_to_seconds_per_beat(bpm)

def generate_melody(num_bars, scale, rest_prob):
  """Generates a random melody."""
  melody = []
  for _ in range(num_bars * TIME_SIGNATURE_NUMERATOR):  # Notes per bar * number of bars
    if random.random() < rest_prob:
      melody.append("R") # Rest
    else:
      melody.append(random.choice(scale))
  return melody

def create_midi_file(melody, filename="ai_music.mid"):
  """Creates a MIDI file from a melody."""
  from midiutil import MIDIFile

  track = 0
  channel = 0
  time = 0  # Start at the beginning
  duration = NOTE_DURATION  # Quarter note

  MyMIDI = MIDIFile(1)  # One track
  MyMIDI.addTempo(track, time, TEMPO)

  pitch_map = {
      "C4": 60, "D4": 62, "E4": 64, "F4": 65, "G4": 67, "A4": 69, "B4": 71,
      "C5": 72, "D5": 74, "E5": 76, "F5": 77, "G5": 79, "A5": 81, "B5": 83,
  }  # MIDI Note Numbers

  volume = 100  # 0-127, how loud the note will be

  for note in melody:
    if note != "R":  # R denotes rest
      try:
          pitch = pitch_map[note]
      except KeyError:
          print(f"Warning: Unknown note {note}, skipping it.")
          time += duration
          continue

      MyMIDI.addNote(track, channel, pitch, time, duration, volume)
    time += duration

  with open(filename, "wb") as output_file:
    MyMIDI.writeFile(output_file)
  print(f"MIDI file '{filename}' created successfully.")


# --- Main ---
if __name__ == "__main__":
  melody = generate_melody(NUM_BARS, SCALE, REST_PROBABILITY)
  print("Generated Melody:", melody)
  create_midi_file(melody)  # Creates ai_music.mid
```
👁️ Viewed: 8

Comments