Java Sound API
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?
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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
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();
Successfully compiled and executed