0

Let say i have a midi file that has 8 bars, 4/4 and 100bpm. i want to split it to 8 equal length midi files. Then combine the 8 bars randomly into a new midi file using Python's Mido or any other library.

I tried to get help from chatgpt, it gave me following code but it just wont work

import mido
import os

# Load the MIDI file
mid = mido.MidiFile('input_file.mid')

# Set the time signature to 4/4
time_signature = mido.MetaMessage('time_signature', numerator=4, denominator=4, clocks_per_click=24, notated_32nd_notes_per_beat=8)
mid.tracks[0].insert(0, time_signature)

# Set the tempo to 100 BPM
tempo = mido.bpm2tempo(100)
set_tempo = mido.MetaMessage('set_tempo', tempo=tempo)
mid.tracks[0].insert(0, set_tempo)

# Calculate the number of ticks per beat and per bar
ticks_per_beat = mid.ticks_per_beat
ticks_per_bar = ticks_per_beat * 4

# Keep track of the current tick position
current_tick = 0
# Keep track of the messages for the current bar
current_bar_messages = []
# Iterate over each message in the MIDI file
for message in mid:
    # Append the message to the current bar
    current_bar_messages.append(message)
    # Increment the current tick position by the message time
    current_tick += message.time
    # If the current tick position is greater than or equal to the number of ticks per bar
    if current_tick >= ticks_per_bar:
        # Create a new MIDI file
        output_file_name = f"bar_{len(os.listdir())}.mid"
        output_mid = mido.MidiFile(type=mid.type)
        # Add a new track to the output MIDI file
        output_mid.add_track()
        # Append the time signature and tempo messages to the new track
        output_mid.tracks[0].append(time_signature)
        output_mid.tracks[0].append(set_tempo)
        # Append all messages up to the current tick position to the new track
        for msg in current_bar_messages:
            output_mid.tracks[0].append(msg)
        # Reset the current tick position and current bar messages
        current_tick = 0
        current_bar_messages = []
        # Save the new MIDI file
        output_mid.save(output_file_name)

memes garage
  • 11
  • 1
  • 1

0 Answers0