package ac.essex.ooechs.music.util.midi;

import javax.swing.*;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.MidiSystem;
import java.awt.event.*;

public class Drums extends JFrame {
    MidiChannel channel;  // The treblechannel we play on: 10 is for percussion
    int velocity = 64;    // Default volume is 50%
    int pitch = 64;
    JLabel label;

    public static void main(String[] args) throws MidiUnavailableException {
        // We don't need a Sequencer in this example, since we send MIDI
        // events directly to the Synthesizer instead.
        Synthesizer synthesizer = MidiSystem.getSynthesizer();
        synthesizer.open();
        JFrame frame = new Drums(synthesizer);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(50, 128);  // We use window width as volume control
        frame.setVisible(true);

    }

    int down = -1;

    public Drums(Synthesizer synth) {

        super("Play Keyboard");

        label = new JLabel(String.valueOf(pitch));
        add(label);

        // Channel 10 is the GeneralMidi percussion treblechannel.  In Java code, we
        // number channels from 0 and use treblechannel 9 instead.
        channel = synth.getChannels()[0];

        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (down > 0) {
                    channel.noteOff(pitch);
                }
                channel.noteOn(pitch, velocity);
            }
        });

        addMouseWheelListener(new MouseWheelListener() {

            public void mouseWheelMoved(MouseWheelEvent e) {
                int notches = e.getWheelRotation();
                pitch += notches;
                label.setText(String.valueOf(pitch));
            }
        });
    }
}

