Solved

Play function

Posted on 2004-10-08
13
210 Views
Last Modified: 2010-03-31

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
Comment
Question by:alvintcc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 4
13 Comments
 
LVL 8

Expert Comment

by:kiranhk
ID: 12259151
check out this,
you can get an idea for your req

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

Kiran
0
 

Author Comment

by:alvintcc
ID: 12331282
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
 
LVL 8

Expert Comment

by:kiranhk
ID: 12341884
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
Industry Leaders: 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!

 

Author Comment

by:alvintcc
ID: 12370783
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
 
LVL 8

Accepted Solution

by:
kiranhk earned 80 total points
ID: 12374087
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
 

Author Comment

by:alvintcc
ID: 12382707
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
 

Author Comment

by:alvintcc
ID: 12383030
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
 

Author Comment

by:alvintcc
ID: 12383157
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
 
LVL 8

Expert Comment

by:kiranhk
ID: 12383210
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
 

Author Comment

by:alvintcc
ID: 12386369
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
 

Author Comment

by:alvintcc
ID: 12386418
Thanks for the link provided. I'm going through again.
0
 

Author Comment

by:alvintcc
ID: 12387790
please help at my selection instrucment drop down list....
I don't know what error occured.
0
 

Author Comment

by:alvintcc
ID: 12393362
any help????????
0

Featured Post

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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

690 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question