Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

Java code implementation that loads a MIDI song file, extracts all notes between two…

  1. User

    Java code implementation that loads a MIDI song file, extracts all notes between two ticks separately to an array that is shuffled and stores the new midi sequence to file shuffle.mid

  2. Assistant

    import javax.sound.midi.*;

    import java.io.*;

    import java.util.*;

    public class MidiShuffle {

    public static void main(String[] args) {

    try {

    // Load the MIDI file

    Sequence sequence = MidiSystem.getSequence(new File("song.mid"));

    // Retrieve the tracks

    Track[] tracks = sequence.getTracks();

    // Find the ticks range to extract notes

    int startTick = 1000;

    int endTick = 5000;

    // Extract all notes between startTick and endTick

    ArrayList notes = new ArrayList<>();

    for (Track track : tracks) {

    for (int i = 0; i < track.size(); i++) {

    MidiEvent event = track.get(i);

    if (event.getTick() >= startTick && event.getTick() <= endTick) {

    if (event.getMessage() instanceof ShortMessage) {

    ShortMessage message = (ShortMessage) event.getMessage();

    if (message.getCommand() == ShortMessage.NOTE_ON) {

    notes.add(event);

    }

    }

    }

    }

    }

    // Shuffle the notes array

    Collections.shuffle(notes);

    // Create a new sequence and add the shuffled notes

    Sequence shuffledSequence = new Sequence(sequence.getDivisionType(), sequence.getResolution());

    Track shuffledTrack = shuffledSequence.createTrack();

    for (MidiEvent event : notes) {

    shuffledTrack.add(event);

    }

    // Save the shuffled sequence to file

    MidiSystem.write(shuffledSequence, 1, new File("shuffle.mid"));

    } catch (Exception e) {

    System.out.println(e.getMessage());

    }

    }

    }