Home  >  Forum  >  Core Java
Post New Query

How to use Sequencer, MidiEvent and ShortMessage to play sound in java



Asked on June 14, 2015
Any one know how to play a song/music/a tone using program/code in java. Is it possible to create a sound effect in java using java code? How to use Sequencer, MidiEvent and ShortMessage for sound.


Replied on June 14, 2015
Yes, It is possible to play a sound using java code.


Replied on June 14, 2015
If you want to play a sound using Java program you MUST import java sound package in your code i.e.
  import javax.sound.midi.*;



Replied on June 14, 2015
Yes u can. 
See the example to play a sound

import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;

public class MiniMusicApp {
public static void main(String[] args) {
 
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}
public void play() {
try{
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage a = new ShortMessage();
a.setMessage(144, 1, 44, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
} catch(Exception ex){
ex.printStackTrace();
}
}

}



Write Answer








©2019 concretepage.com | Privacy Policy | Contact Us