JAVA HeadFirst MiniMusic Code

Here is the full code for the program. In addition to that, you need to make sure you have the soundbank in your JRE folder. Google JAVA Soundbank to download the file. And then extract the file in the following folder

C:\Program Files\Java\jre1.8.0_121\lib\audio (OR)

C:\Program Files\Java\jre<VERSION>\lib\audio

C:\Users\MM\Google Drive\PROGRAMMING\Java\MiniMusicCmdLine\src\minimusiccmdline>javac MiniMusicCmdLine.java

C:\Users\MM\Google Drive\PROGRAMMING\Java\MiniMusicCmdLine\src\minimusiccmdline>cd ..

C:\Users\MM\Google Drive\PROGRAMMING\Java\MiniMusicCmdLine\src>java minimusiccmdline.MiniMusicCmdLine 102 33

THE PROGRAM:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
PAGE 346, Chapter 11 (PDF Page 379)
*/
package minimusiccmdline;

import javax.sound.midi.*;

/**
*
* @author mustnap
*/
public class MiniMusicCmdLine {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
MiniMusicCmdLine mini = new MiniMusicCmdLine();
if (args.length < 2) {
System.out.println(“Don’t forget the instrument and note args”);
} else {
int instrument = Integer.parseInt(args[0]);
int note = Integer.parseInt(args[1]);
mini.play(instrument, note);
}

} // close main

public void play(int instrument, int note) {

try {
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
MidiEvent event = null;

ShortMessage first = new ShortMessage();
first.setMessage(192, 1, instrument, 0);
MidiEvent changeInstrument = new MidiEvent(first, 1);
track.add(changeInstrument);
ShortMessage a = new ShortMessage();
a.setMessage(144, 1, note, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, note, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();

Thread.sleep(2000);
player.close();
System.exit(0);

} catch (Exception ex) {
ex.printStackTrace();
}

} // close playe

} //close class

Leave a Reply

Your email address will not be published. Required fields are marked *