Home > Articles > Programming > Java

Making Waves with Java—An Adventure in Midi

  • Print
  • + Share This
Java expert Mark Wutka shows you how to build your own white noise machine using a Midi synthesizer, which is included on most sound drivers for Windows, and the javax.sound.midi API, which is new to JDK 1.3. Follow Mark's directions, and you'll be sleeping like a baby in no time!
Java expert Mark Wutka shows you how to build your own white noise machine using a Midi synthesizer, which is included on most sound drivers for Windows, and the javax.sound.midi API, which is new to JDK 1.3. Follow Mark's directions, and you'll be sleeping like a baby in no time!

My wife and I use one of those sound-generator boxes when we go to sleep at night to drown out any surrounding noise. Recently, we were visiting my mom and discovered that we should have packed the sound generator in our suitcase. It seems that her next-door neighbor has a very annoying dog named Henry who barks at us all night. You'd think he had discovered a stadium full of mailmen! I decided to see if I could use Java to make my own sound generator.

My first thought was that I could create an audio file containing white noise. After looking over the new javax.sound.sampled package in JDK 1.3, however, I decided that unless I could figure out the format for one of the supported audio files, I was out of luck. I happened to remember, though, that my Midi synthesizer has a wave sound—maybe I had it on Windows, too (most sound drivers for Windows include a Midi synthesizer that plays sounds on your speaker just like they were WAV files). I decided to explore the javax.sound.midi API, also new to JDK 1.3.

I am by no means a Midi expert. I have a synthesizer, and I have used Midi programs in the past, so I am at least a little familiar with Midi. Basically, Midi is a protocol for musical instruments. You can chain multiple Midi devices together, and each device has its own specific ID. Some devices only play music; others only generate notes. Some devices, like my synthesizer, generate notes and also play them. Each device has a number of channels (usually 16), which function a little like sessions. The idea is that you can make each channel function as a different instrument and play different notes.

A Midi patch describes an instrument. It contains a sound bank number (a synthesizer typically has a number of different sound banks containing many instruments) and a program number, which is the index number of the instrument in the particular sound bank. To change the instrument on a channel, you issue a program change request, supplying a new patch (instrument).

To play musical notes, you simply send the channel a "note on" request, giving the pitch value (a number between 0 and 127, where 64 is middle C) and the velocity, which indicates how hard you want the note struck. For example, on a piano, when you hit a key harder, the sound is louder. Midi supports the same concept, and some synthesizers even have velocity-sensitive keys. When you want the note to stop, you send a "note off" request. Midi has other interesting requests, such as "pitch bend," which enables you to change the pitch of the note on the fly. On a synthesizer, you often see a pitch-bend wheel off to the left that can raise or lower the pitch. It's basically the same effect that you get on a guitar when you push the string out of position. A single channel can typically support a number of simultaneous notes. To play a chord, you don't need to use separate channels; just send three "note on" requests.

One of the interesting aspects of the synthesizer is that a drum kit is a single instrument. For instance, you may have an instrument called Jazz Drums in which each different note is a different drum. A single note might represent cymbals, a high hat, or even a whistle. You might need to play around with the synthesizer a bit to figure them out.

In starting my sound-generator project, I had never used the Java Midi API, so I had to take a few guesses about where to start. From my limited knowledge of Midi, I knew that my initial goal was just to be able to send a note on a channel and hear it played.

Looking at the API, the MidiSystem class sure looks like the main entry point into the system—and, sure enough, it has a method to return the default synthesizer. That certainly looks like a good place to start. You simply call getSynthesizer like this:

Synthesizer synth = MidiSystem.getSynthesizer();

Looking at the Synthesizer class, you can see that it has a getChannels method, so that looks like the best way to get a channel. It also has open and close methods (inherited from the MidiDevice parent class), so obviously you need to open the synthesizer device before you can use it. You simply call the open method like this:

synth.open();

Looking at the MidiChannel interface, you can see that it has noteOn and noteOff methods, so it's a pretty good guess that you can use these to play notes. You just call getChannels on the Synthesizer class to get the available channels, and then you play a note on one of the channels:

MidiChannel[] channels = synth.getChannels();

channels[1].noteOn(64, 127);

You want to give the note some time to play before you shut it off. I tried doing a Thread.sleep before shutting it off:

Thread.sleep(2000);
channels[1].noteOff(64);

Finally, when you're done with the synthesizer, you should close it:

synth.close();

When I ran my first test program, I noticed that it never terminated even after I closed the synthesizer. Obviously the Midi library was doing something in the background that prevented the program from terminating. I threw in a call to System.exit to get it to quit properly.

At this point, I had a program that could play a C note on what sounded like a piano. Here is the complete program:

import javax.sound.midi.*;

public class Note
{
    public static void main(String[] args)
    {
        try
        {
// Locate the default synthesizer
            Synthesizer synth = MidiSystem.getSynthesizer();

// Open the synthesizer
            synth.open();

// Get the available Midi channels - there are usually 16
            MidiChannel channels[] = synth.getChannels();

// Play a note on channel 1
            channels[1].noteOn(64, 127);
            
// Give the note some time to play
            Thread.sleep(2000);

// Turn the note off
            channels[1].noteOff(64);

// Close the synthesizer device
            synth.close();

// Terminate the program
            System.exit(0);
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}

Okay, I knew that I could play a note. The next task was to play a note that sounded like the ocean. I didn't know the bank number or the patch number for the ocean sound—and, for that matter, I didn't know the name of the instrument. The Synthesizer class contains a getLoadedInstruments method that returns a list of all the instruments loaded into the sound bank. I tried calling it and I got a zero-length array—there were no instruments loaded.

The Synthesizer class also contains a loadAllInstruments method, so I had a way to load instruments—but loadAllInstruments takes a Soundbank object as a parameter. Seeing that the Synthesizer class had a getDefaultSoundbank method, I tried the following code:

Soundbank bank = synth.getDefaultSoundbank();
synth.loadAllInstruments(bank);

Sure enough, when I called getLoadedInstruments, I got a bunch. I listed them out using the following code:

Instrument instrs[] = synth.getLoadedInstruments();
for (int i=0; i < instrs.length; i++)
{
    System.out.println(instrs[i].getName());
}

Somewhere in that huge list of names, I saw Seashore, so I changed the loop to look for an instrument named Seashore. Now that I had the instrument, I needed to figure out how to change the channel to use the instrument. I knew that I needed to issue a program change on the channel, and the programChange method takes a program number (really an instrument number) and an optional sound bank. The Instrument class doesn't have a program number or a sound bank number, but it does have a getPatch method that returns a Patch object that does contain a program number and a sound bank.

I called programChange on the channel like this:

Patch seashorePatch = seashore.getPatch();
channels[1].programChange(seashorePatch.getBank(),
    seashorePatch.getProgram());

Sure enough, when I played the C note, I heard an ocean sound. The only problem left was that the ocean sound was a little too regular for me. I didn't think I could go to sleep with such a simple sound repetition. I decided to start five different ocean sounds with slightly different pitches and at staggered intervals so that the sounds should run together. I ended up with the following program, which, I am happy to say, drowned out Henry's annoying bark.

import javax.sound.midi.*;

public class Waves
{
    public static void main(String[] args)
    {
        try
        {
// Locate the default synthesizer
            Synthesizer synth = MidiSystem.getSynthesizer();

// Open the synthesizer
            synth.open();

// Get the available Midi channels - there are usually 16
            MidiChannel channels[] = synth.getChannels();

// Get the synth's soundbank where all the sounds are stored
            Soundbank bank = synth.getDefaultSoundbank();

// Load all the available instruments
            synth.loadAllInstruments(bank);

// Get a list of the available instruments
            Instrument instrs[] = synth.getLoadedInstruments();

            Instrument seashore = null;

// Loop through the instruments
            for (int i=0; i < instrs.length; i++)
            {

// Stop when you find the seashore
                if (instrs[i].getName().equals("Seashore"))
                {
                    seashore = instrs[i];
                    break;
                }
            }

            if (seashore == null)
            {
                System.out.println("Can't find the beach");
                System.exit(0);
            }

// Get the information describing the Seashore instrument - the
// patch contains the soundbank and program number
            Patch seashorePatch = seashore.getPatch();

// Set 5 channels to use the Seashore instrument
            channels[1].programChange(seashorePatch.getBank(),
                seashorePatch.getProgram());
            channels[2].programChange(seashorePatch.getBank(),
                seashorePatch.getProgram());
            channels[3].programChange(seashorePatch.getBank(),
                seashorePatch.getProgram());

// Start the Seashore note on 3 different channels. By waiting a short
// time before starting the next note, you get a much more continuous sound
            channels[1].noteOn(32, 127);
            Thread.sleep(3500);
            channels[2].noteOn(32, 127);
            Thread.sleep(1500);
            channels[3].noteOn(32, 127);

// Wait forever
            for (;;)
            {
                try { Thread.sleep(999999999); } catch (Exception ignore) {}
            }
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}

The entire development process for this little project took no more than 30 minutes. If you have at least a small idea how Midi works, the Midi API is very intuitive. Bravo, Javasoft!

About the Author

Mark Wutka is the president of Wutka Consulting and specializes in helping companies get the most out of Java. He has built numerous Java, JSP, and servlet applications, including several online ordering applications. In a past life, he was the chief architect on a large, object-oriented distributed system providing automation for the flight operations division of a major airline; for nine years he designed and implemented numerous systems in Java, C, C++, and Smalltalk for that same airline. Mark previously contributed chapters to Special Edition Using Java 2 Platform and is the author of Special Edition Using Java Server Pages and Servlets and Hacking Java. His next book, Special Edition Using Java 2 Enterprise Edition, will be available in April.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020