Java Sound API
Last Updated :
17 May, 2022
JavaSound is a collection of classes and interfaces for effecting and controlling sound media in java. It consists of two packages.
- javax.sound.sampled: This package provides an interface for the capture, mixing digital audio.
- javax.sound.midi: This package provides an interface for MIDI (Musical Instrument Digital Interface) synthesis, sequencing, and event transport.
What is MIDI?
We will be exploring MIDI more about MIDI here. So MIDI is like a sheet of notes that the midi capable instrument can play, think of it as an HTML document and midi capable instrument as a web browser. MIDI file has information about how a song should be played, just like an instruction sheet for a guitar player. MIDI devices know how to read a midi file and generate sound.
In order to make actual sound we need four things for this:
- Instrument (that plays the music) SEQUENCER
- Song (the music to be played) SEQUENCE
- Track (which holds the notes)
- Notes (the actual music information) MIDI EVENTS
JavaSound API got all of these covered.
SEQUENCER ⇒ SEQUENCE ⇒ TRACK ⇒ MIDI EVENTS
Procedure:
Step 1: Get a Sequencer and open it
// Make a sequencer named player and open it
Sequencer player = MIDISystem.getSequencer();
player.open();
Step 2: Make a new Sequence
// Make a new sequence
Sequence seq = new Sequence(Sequence.PPQ, 4);
Step 3: Get a new Track from the Sequence
// Creating new Track
Track t = seq.createTrack();
Step 4: Fill the Track with MIDIEVENTS
// Filling the Track with MidiEvent and
// giving the Sequence to the Sequencer
t.add(myMidiEvent1);
player.setSequence(seq);
// Play it using start
player.start();
Implementation:
Example
Java
import javax.sound.midi.*;
public class GFG {
public static void main(String[] args)
{
GFG minimusic = new GFG();
minimusic.play();
System.out.print(
"Successfully compiled and executed" );
}
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();
}
}
}
|
Output:
Successfully compiled and executed
Share your thoughts in the comments
Please Login to comment...