Code is not working

I’ve been using ChatGPT to write this code (I have no idea how to code in python) to convert a midi file into a note format and the duration of the note. The note name part is working fine, it’s just the durations part that isn’t working. All the durations are the same when they should be different. Can anyone help? Here’s my code:

try:
    import mido
except ImportError:
    print("Please install the mido library by running: pip install mido")
    exit()

def midi_to_note(midi_note):
    notes = ['C', 'CS', 'D', 'DS', 'E', 'F', 'FS', 'G', 'GS', 'A', 'AS', 'B']
    note_name = notes[midi_note % 12]
    octave = (midi_note // 12) - 1
    return f"NOTE_{note_name}{octave}"

def convert_midi_file(file_path):
    try:
        midi_file = mido.MidiFile(file_path)
        ticks_per_beat = midi_file.ticks_per_beat
        microseconds_per_beat = 500000  # Assuming 120 BPM
        ticks_per_second = ticks_per_beat / (microseconds_per_beat / 1000000)

        notes_list = []
        durations_list = []

        current_time = 0
        note_on = {}

        for msg in midi_file:
            current_time += msg.time
            if msg.type == 'note_on':
                note_on[msg.note] = current_time
            elif msg.type == 'note_off':
                note_off_time = current_time
                duration_ticks = note_off_time - note_on.get(msg.note, 0)
                duration_seconds = duration_ticks / ticks_per_second
                print("Duration (seconds):", duration_seconds)  # Add this line
                if duration_seconds > 0:
                    note = midi_to_note(msg.note)
                    if duration_seconds <= 0.125:
                        duration = 4  # Quarter note
                    elif duration_seconds <= 0.25:
                        duration = 2  # Half note
                    elif duration_seconds <= 0.5:
                        duration = 1  # Whole note
                    else:
                        duration = int(1 / duration_seconds)  # Calculate other durations
                    notes_list.append(note)
                    durations_list.append(duration)

        return notes_list, durations_list

    except Exception as e:
        print(f"Error processing MIDI file: {e}")
        return None, None

def main():
    file_path = input("Enter the path to the MIDI file: ")
    # Remove the extra '.mid' extension if present
    if file_path.lower().endswith('.mid.mid'):
        file_path = file_path[:-4]
    notes_list, durations_list = convert_midi_file(file_path)
    if notes_list:
        print("Notes:")
        print(', '.join(notes_list))
        print("Durations:")
        print(', '.join(map(str, durations_list)))

if __name__ == "__main__":
    main()

it’s just gibberish.

The Beginner’s Guide on the wiki has an extensive collection of resources for learning how to code in Python.

ChatGPT has no idea how to code in Python either. Don’t use it.

1 Like

If you want to understand how to write code, then you should start learning how to write code, by following a tutorial and/or getting instruction.

If you want ChatGPT to make working programs for you, then you should prepare to be disappointed. If ChatGPT could just make every program that everyone wants from a suitable description, and they actually worked, we would be living in a completely different world.

If you are hoping as a beginner that ChatGPT can give you a leg up in learning Python, that simply doesn’t work like you’d expect it to. ChatGPT literally isn’t thinking and doesn’t understand its output:

2 Likes

The problem isn’t that computers aren’t good enough to write programs. The problem is that any description good enough to create a useful program from would itself be a program. That is a fundamental.

We don’t write raw machine code. We don’t write in assembly languages. We usually don’t spend a lot of our time writing in C. We use Python (and other high level languages) because computers do a good job at writing low level code to fulfil our high level requests; but those high level requests are still programs.

But ChatGPT is not a tool for writing programs. It is a chatbot. It’s like going to a therapist and discussing your struggles with a technical problem - you might get a sympathetic ear, but you won’t get technical expertise.

4 Likes

If ChatGPT were only a chatbot, it would have “chat” in its name, wouldn’t it?

Oh… wait… :slight_smile:

2 Likes

Off topic: ever considered fiddling around with a midi editor? :smiley::ok_hand:

I’ve made a lot of programs over the decades that create, parse, or manipulate MIDI files. It’s a pretty easy format to work with (although you kinda have to have a full table of message types in order to decode track data), so the OP’s basic idea is sound. [1] Or are you saying that a MIDI editor would be a fun project to write in Python? Because I can totally see that too.


  1. Badum tish ↩︎

FWIW, I also wrote a MIDI manipulation program once - for a very specialized purpose, and before mido existed (or at least any of the PyPI history). I agree that it’s easy enough to work with, but it sure isn’t elegant. It was definitely not designed to be the tracker format that many people would like it to be. It’s designed for recording live sessions and knowing who played what.

Yeah, it’s meant to recreate a real-time message stream. Still, it does a decent job of recording events; it’s not a sheet music format though.

That’s nice, not sure whether it helps YELL0W