Solved

Play function

Posted on 2004-10-08
13
200 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
  • 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
 

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

705 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now