• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 215
  • Last Modified:

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?
0
alvintcc
Asked:
alvintcc
  • 9
  • 4
1 Solution
 
kiranhkCommented:
check out this,
you can get an idea for your req

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

Kiran
0
 
alvintccAuthor Commented:
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?
0
 
kiranhkCommented:
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/
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
alvintccAuthor Commented:
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 :)
0
 
kiranhkCommented:
The following is the code for displaying and playing the keyboard/piano in the
http://java.sun.com/products/java-media/sound/samples/JavaSoundDemo/        example


 
    /**
     * 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
0
 
alvintccAuthor Commented:
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);
    }
}
0
 
alvintccAuthor Commented:
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]);
       
     
   
0
 
alvintccAuthor Commented:
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(); }
    }
0
 
kiranhkCommented:
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.
0
 
alvintccAuthor Commented:
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);
     } */
0
 
alvintccAuthor Commented:
Thanks for the link provided. I'm going through again.
0
 
alvintccAuthor Commented:
please help at my selection instrucment drop down list....
I don't know what error occured.
0
 
alvintccAuthor Commented:
any help????????
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 9
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now