Home » Blog » Sound effects and Musical Notes.

Share This Post

Java / Main Slider

Sound effects and Musical Notes.

Sound effects and Musical Notes.

Sound Effects and Musical Notes

I will demo how to play a wave file or other sound files as effects. How to play musical notes. Later I will write on how to play music files simultaneously with sound effects.  There is a website that is like a YouTube for sound effects. freesound.org is a website where anyone can get an account to upload sound effects that they have recorded. So you too can record and contribute.  Sox Wikipedia and Sox Sourceforge is a command line sound conversion tool where you may convert most any format found on freesound.org to .wav for use in your Java software.

Listen to my Podcast about 2D Game coding.

Playing WAV Sound Effects

I now show you how to play some sound effects. I have a small collection of wave files for a beaver trapping game. One of the files threw an exception because of the exact format. I'm not sure how to fix it right now. You will notice a lot of repetitive code in this example. I was working with so many sound files that it needs a refactor. A new object needs to be created.  Much of that can be performed maybe only once in one object. If you want to try out refactoring be my guest.

Below is a link to a zip file that contains the wave files for this example. When I tested this download I was given a security alert telling me could be a very naughty file. It might be because I used jar tool to jar the wave files and named it .zip and not .jar.

wav.zip download

Clip | AudioInputStream

import java.io.*;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.event.*;

public class PlaySoundEffects{
 public PlaySoundEffects(){
  try{
   File swimFile = new File("swim1.wav");
   File pondFile = new File("pond1.wav");
   File splashFile = new File("splash1.wav");
   File walkingFile = new File("walking1.wav");
   File trapCatchFile = new File("trapcatch1.wav");
   File trapPlaceFile = new File("trapplace1.wav");
   File waterFile = new File("water1.wav");
   File beaverWalkFile = new File("beaverwalk1.wav");
   AudioInputStream swimIn = AudioSystem.getAudioInputStream(swimFile);
   AudioInputStream pondIn = AudioSystem.getAudioInputStream(pondFile);
   AudioInputStream splashIn = AudioSystem.getAudioInputStream(splashFile);
   AudioInputStream walkingIn = AudioSystem.getAudioInputStream(walkingFile);
   AudioInputStream waterIn = AudioSystem.getAudioInputStream(waterFile);
   AudioInputStream trapCatchIn = AudioSystem.getAudioInputStream(trapCatchFile);
   //AudioInputStream trapPlaceIn = AudioSystem.getAudioInputStream(trapPlaceFile);
   AudioInputStream beaverIn = AudioSystem.getAudioInputStream(beaverWalkFile);
   Clip pondClip = AudioSystem.getClip();
   Clip swimClip = AudioSystem.getClip();
   Clip splashClip = AudioSystem.getClip();
   Clip walkingClip = AudioSystem.getClip();
   Clip waterClip = AudioSystem.getClip();
   Clip trapCatchClip = AudioSystem.getClip();
   //Clip trapPlaceClip = AudioSystem.getClip();
   Clip beaverClip = AudioSystem.getClip();
   JFrame aFrame=new JFrame("Sound Effects");
   JPanel aPanel=new JPanel();
   JButton pondButton = new JButton("Pond");
   JButton swimButton = new JButton("Swim");
   JButton splashButton = new JButton("Splash");
   JButton walkingButton = new JButton("Walking");
   JButton waterButton = new JButton("Water");
   JButton trapCatchButton = new JButton("TrapCatch");
   //JButton trapPlaceButton = new JButton("TrapPlace");
   JButton beaverButton = new JButton("Beaver");
   aFrame.setContentPane(aPanel);
   aPanel.add(pondButton);
   aPanel.add(swimButton);
   aPanel.add(splashButton);
   aPanel.add(walkingButton);
   aPanel.add(waterButton);
   aPanel.add(trapCatchButton);
   //aPanel.add(trapPlaceButton);
   aPanel.add(beaverButton);
   pondClip.open(pondIn);
   swimClip.open(swimIn);
   splashClip.open(splashIn);
   walkingClip.open(walkingIn);
   waterClip.open(waterIn);
   trapCatchClip.open(trapCatchIn);
   beaverClip.open(beaverIn);
   aFrame.pack();                                       
   aFrame.setDefaultCloseOperation(aFrame.EXIT_ON_CLOSE);
   aFrame.show();
   pondButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    pondClip.start();
    Thread.sleep(3000);
    pondClip.stop();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );
    swimButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    swimClip.start();
    Thread.sleep(3000);
    swimClip.stop();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );
   splashButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    splashClip.start();
    Thread.sleep(3000);
    splashClip.stop();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );
   walkingButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    walkingClip.start();
    Thread.sleep(3000);
    walkingClip.stop();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );
   waterButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    waterClip.start();
    Thread.sleep(3000);
    waterClip.stop();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );
   trapCatchButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    
    trapCatchClip.start();
    Thread.sleep(3000);
    trapCatchClip.stop();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );
   /*trapPlaceButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    clip.open(trapPlaceIn);
    clip.start();
    Thread.sleep(3000);
    clip.close();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );*/
   beaverButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {
   try{
    
    beaverClip.start();
    Thread.sleep(3000);
    beaverClip.stop();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
   );
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 public static void main(String args[]){
  new PlaySoundEffects();
 }
}

 

Playing MIDI Musical Notes

In the example below I show you how to play some random music notes using any of 128 instruments found on your sound card. The play button plays 10 random notes of random duration. The Prev and Next buttons move through a list of Instruments displayed in the label to the right. In the console, I listed all the instruments on the sound card.

There are some other things we could do here that I have yet to figure out how to do. The volume of the note being played can be changed. The firmness of a key strike can be adjusted. Also with voices, we can alter how many notes are played at once so that you may play a chord. Different sound cards have different synthesizers. So they vary in how many voices you can play at once. They differ also in the number of banks. In this example, we used only the 0 bank. There are others and I have yet to figure out how to change the bank number. Also, there are midi channels. So you can play more than one type of instrument at the same time.

Playing Music in Java (Oracle) | SynthesizerMidiChannel | SoundBank

Probably the better way to do the MIDI music is in using a 3rd party API. And I have yet to try any out.

Listing instruments found on sound card.

Musical Instruments

import javax.sound.midi.*;
import javax.swing.*;
import java.awt.event.*;

public class SoundNotes {
 Instrument[] instr =null;
 Synthesizer synth = null;
 boolean skip=false;
 int duration=0;
 int note=0;
 int instrument=0;
 MidiChannel[] mc=null;
 public static void main(String[] args) {
  new SoundNotes();
 }
 public SoundNotes(){
  try{
   synth = MidiSystem.getSynthesizer();
   synth.open();                                   
   instr = synth.getDefaultSoundbank().getInstruments();
   for(int i=0;i<instr.length;i++)
   	System.out.println(instr[i]);
  }catch(MidiUnavailableException mue){
   mue.printStackTrace();
  }
  mc = synth.getChannels();
  JFrame frame = new JFrame("Sound1");                
  JPanel pane = new JPanel();                         
  JButton playButton = new JButton("Play");
  JButton prevButton = new JButton("Prev");
  JButton nextButton = new JButton("Next");
  JLabel instrumentLabel=new JLabel(instr[instrument].toString());
  frame.getContentPane().add(pane);                   
  pane.add(playButton);
  pane.add(prevButton);
  pane.add(nextButton);
  pane.add(instrumentLabel);
  frame.pack();                                       
  frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
  frame.show();
  synth.loadInstrument(instr[instrument]);
  mc[1].programChange(instr[instrument].getPatch().getProgram());
  playButton.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {  
    play10Notes();
   }
  });   
  prevButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
   instrument--;
   if(instrument==-1)instrument=127;
   synth.loadInstrument(instr[instrument]);
   mc[1].programChange(instr[instrument].getPatch().getProgram());
   instrumentLabel.setText(instr[instrument].toString());
   frame.pack();
  }});
  nextButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
   instrument++;
   if(instrument==128)instrument=0;
   synth.loadInstrument(instr[instrument]);
   mc[1].programChange(instr[instrument].getPatch().getProgram());
   instrumentLabel.setText(instr[instrument].toString());
   frame.pack();
  }});
 }
 void play10Notes(){
  for(int i=0;i<10;i++){
   note = (int)(Math.random() * 127 + 1);
   duration = (int)(Math.random() * 100 + 1);
   try{
 mc[1].noteOn(note,400);
 Thread.sleep(duration*10);
   }catch(InterruptedException ie){
 ie.printStackTrace();   
   }
  }
  try{
   Thread.sleep(1000);
   mc[1].allNotesOff();
   Thread.sleep(1000);
  }catch(InterruptedException ie){
   ie.printStackTrace();   
  }
 }
}

 

Share This Post

Leave a Reply