Link to home
Start Free TrialLog in
Avatar of alvintcc
alvintcc

asked on

Play function


How to display a musical keyboard to let user play by clicking the note.

This is my instrument selection

Instrument instruments[]=synth.getAvailableInstruments();
synth.loadInstrument(instruments[80]);
channels[0].programChange(80);

how to make the output music according to the selected instructment?
Any expert able to provide sample for me?
Avatar of kiranhk
kiranhk

check out this,
you can get an idea for your req

http://java.sun.com/products/java-media/sound/samples/JavaSoundDemo/

Kiran
Avatar of alvintcc

ASKER

This sample too complicated for me.I can't understand the code. I have tried to go through it many times.I can't specify which part is displaying the keyboard and the fuction of instrucment. Any other sample more easier to understand?
did u check this out

Introduction to Java sound
http://www.onjava.com/pub/a/onjava/excerpt/jenut3_ch17/

Simple Examples on Java sound
http://www.jsresources.org/examples/
Can you specify the code of DISPLAYING KEYBOARD and PLAYING KEYBOARD?
I'm trying to do the drop down list to select the instrucment but it doesn't work.
      Choice sound;
      Synthesizer synth;
      Instrument instruments[] = synth.getAvailableInstruments();
      for ( int j = 0; j < instruments.length; j++ )
       {
      add(sound);
      sound.addItem(instruments[j].getName());
      sound.setBackground(Color.lightGray);
                sound.addItemListener(this);
      }

Hope to get help..thanks in advance :)
ASKER CERTIFIED SOLUTION
Avatar of kiranhk
kiranhk

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for showing the section. It helps.
I tried to modify the code. I able to display the keyboard but couldn't play it yet.
I tried to make a pull down menu to choose instruments but it couldn't run the program when i typed below code:


    //Instrument instruments[]= synthesizer.getAvailableInstruments();

      /*for ( int j = 0; j < instruments.length; j++ )
       {
      p.add(sound);
      sound.addItem(instruments[j].getName());
      sound.setBackground(Color.lightGray);
      } */



This is my code. How to make the keyboard able to be played with different instrument selected from pull down menu? Can you fix the problem for me? Hope to get your help as soon as possible. Thanks.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.sound.midi.*;
import java.util.Vector;

public class MidiSynth extends JPanel{

    final int NOTEON = 144;
    final int NOTEOFF = 128;
      final int ON = 0, OFF = 1;
    final Color jfcBlue = new Color(204, 204, 255);
    final Color pink = new Color(255, 175, 175);
    Vector keys = new Vector();
    Vector whiteKeys = new Vector();
    JCheckBox mouseOverCB = new JCheckBox("mouseOver", true);
    Piano piano;
    Sequencer sequencer;
    Sequence sequence;
    Synthesizer synthesizer;
    //Instrument instruments[]= synthesizer.getAvailableInstruments();
    Choice sound = new Choice();
   

    public MidiSynth() {
        JPanel p = new JPanel();
      p.add(piano = new Piano());
      p.add(mouseOverCB);
     
      /*for ( int j = 0; j < instruments.length; j++ )
       {
      p.add(sound);
      sound.addItem(instruments[j].getName());
      sound.setBackground(Color.lightGray);
      } */
       add(p);
    }
 
 
    /**
     * Black and white keys or notes on the piano.
     */
    class Key extends Rectangle {
        int noteState = OFF;
        int kNum;
        public Key(int x, int y, int width, int height, int num) {
            super(x, y, width, height);
            kNum = num;
        }
        public boolean isNoteOn() {
            return noteState == ON;
        }
        public void on() {
            setNoteState(ON);
            //cc.channel.noteOn(kNum, cc.velocity);
           /* if (record) {
                createShortEvent(NOTEON, kNum);
            }*/
        }
        public void off() {
            setNoteState(OFF);
            //cc.channel.noteOff(kNum, cc.velocity);
           /* if (record) {
                createShortEvent(NOTEOFF, kNum);
            }*/
        }
        public void setNoteState(int state) {
            noteState = state;
        }
    } // End class Key



    /**
     * Piano renders black & white keys and plays the notes for a MIDI
     * channel.  
     */
    class Piano extends JPanel implements MouseListener {

        Vector blackKeys = new Vector();
        Key prevKey;
        final int kw = 16, kh = 80;


        public Piano() {
            setLayout(new BorderLayout());
            setPreferredSize(new Dimension(42*kw, kh+1));
            int transpose = 24;  
            int whiteIDs[] = { 0, 2, 4, 5, 7, 9, 11 };
         
            for (int i = 0, x = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++, x += kw) {
                    int keyNum = i * 12 + whiteIDs[j] + transpose;
                    whiteKeys.add(new Key(x, 0, kw, kh, keyNum));
                }
            }
            for (int i = 0, x = 0; i < 6; i++, x += kw) {
                int keyNum = i * 12 + transpose;
                blackKeys.add(new Key((x += kw)-4, 0, kw/2, kh/2, keyNum+1));
                blackKeys.add(new Key((x += kw)-4, 0, kw/2, kh/2, keyNum+3));
                x += kw;
                blackKeys.add(new Key((x += kw)-4, 0, kw/2, kh/2, keyNum+6));
                blackKeys.add(new Key((x += kw)-4, 0, kw/2, kh/2, keyNum+8));
                blackKeys.add(new Key((x += kw)-4, 0, kw/2, kh/2, keyNum+10));
            }
            keys.addAll(blackKeys);
            keys.addAll(whiteKeys);

            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseMoved(MouseEvent e) {
                    if (mouseOverCB.isSelected()) {
                        Key key = getKey(e.getPoint());
                        if (prevKey != null && prevKey != key) {
                            prevKey.off();
                        }
                        if (key != null && prevKey != key) {
                            key.on();
                        }
                        prevKey = key;
                        repaint();
                    }
                }
            });
            addMouseListener(this);
        }

        public void mousePressed(MouseEvent e) {
            prevKey = getKey(e.getPoint());
            if (prevKey != null) {
                prevKey.on();
                repaint();
            }
        }
        public void mouseReleased(MouseEvent e) {
            if (prevKey != null) {
                prevKey.off();
                repaint();
            }
        }
        public void mouseExited(MouseEvent e) {
            if (prevKey != null) {
                prevKey.off();
                repaint();
                prevKey = null;
            }
        }
        public void mouseClicked(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }


        public Key getKey(Point point) {
            for (int i = 0; i < keys.size(); i++) {
                if (((Key) keys.get(i)).contains(point)) {
                    return (Key) keys.get(i);
                }
            }
            return null;
        }

        public void paint(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            Dimension d = getSize();

            g2.setBackground(getBackground());
            g2.clearRect(0, 0, d.width, d.height);

            g2.setColor(Color.white);
            g2.fillRect(0, 0, 42*kw, kh);

            for (int i = 0; i < whiteKeys.size(); i++) {
                Key key = (Key) whiteKeys.get(i);
                if (key.isNoteOn()) {
                   //g2.setColor(record ? pink : jfcBlue);
                    g2.fill(key);
                }
                g2.setColor(Color.black);
                g2.draw(key);
            }
            for (int i = 0; i < blackKeys.size(); i++) {
                Key key = (Key) blackKeys.get(i);
                if (key.isNoteOn()) {
                    //g2.setColor(record ? pink : jfcBlue);
                    g2.fill(key);
                    g2.setColor(Color.black);
                    g2.draw(key);
                } else {
                    g2.setColor(Color.black);
                    g2.fill(key);
                }
            }
        }
    } // End class Piano


    public static void main(String args[]) {
        final MidiSynth midiSynth = new MidiSynth();
        JFrame f = new JFrame("Midi Synthesizer");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
        f.getContentPane().add("Center", midiSynth);
        f.pack();
        f.setVisible(true);
    }
}
What does these code means in the sample "MidiSynth" file, in section void open()?

       >     sequencer = MidiSystem.getSequencer();
       >   sequence = new Sequence(Sequence.PPQ, 10);

        >    instruments = synthesizer.getDefaultSoundbank().getInstruments();
        >    synthesizer.loadInstrument(instruments[0]);
       
     
   
What does this code purpose (in MidiSynth file)
 /**
     * given 120 bpm:
     *   (120 bpm) / (60 seconds per minute) = 2 beats per second
     *   2 / 1000 beats per millisecond
     *   (2 * resolution) ticks per second
     *   (2 * resolution)/1000 ticks per millisecond, or
     *      (resolution / 500) ticks per millisecond
     *   ticks = milliseconds * resolution / 500
     */
    public void createShortEvent(int type, int num) {
        ShortMessage message = new ShortMessage();
        try {
            long millis = System.currentTimeMillis() - startTime;
            long tick = millis * sequence.getResolution() / 500;
            message.setMessage(type+cc.num, num, cc.velocity);
            MidiEvent event = new MidiEvent(message, tick);
            track.add(event);
        } catch (Exception ex) { ex.printStackTrace(); }
    }
You can check out the 3 examples below abt how to load the synthesizer and the Sound bank for playing the sound. then u can easily link your piano to ur sound. This will give you a step by step idea abt what u need to do for ur program to work

http://www.jsresources.org/examples/midi_synthesizer.html

you can also check out this for learning abt what is being used when playing sound

http://java.sun.com/developer/technicalArticles/Media/JavaSoundAPI/


PS: sorry, no spoon feeding, or full code.
Alrite. Then can you tell me why program couldn't run when i typed below code for choosing to play sound.Is it correct the code?There is no error occured when i compile but it makes the program couldn't run. I can't do further steps if this not solved. Please help me at this stage..


    //Instrument instruments[]= synthesizer.getAvailableInstruments();

     /*for ( int j = 0; j < instruments.length; j++ )
      {
     p.add(sound);
     sound.addItem(instruments[j].getName());
     sound.setBackground(Color.lightGray);
     } */
Thanks for the link provided. I'm going through again.
please help at my selection instrucment drop down list....
I don't know what error occured.
any help????????