29

I am working with a SMS handling, java based software and want to play a beep / alert sound whenever we receive a message. I tried looking at the java.sound libraries and could not find anything. I do not know if going the applet way of playing a sound will be okay in a java application! Are there any predefined sounds in any java libraries which we can call in an application? Any pointers will be appreciated!

Krithika
  • 291
  • 1
  • 3
  • 3

5 Answers5

58

If you just want to produce a beep or a quick alert, you can use the following code:

import java.awt.Toolkit;
Toolkit.getDefaultToolkit().beep();
Andreas Violaris
  • 2,465
  • 5
  • 13
  • 26
Sean
  • 7,597
  • 1
  • 24
  • 26
42

You can generate your own sound if you looking for something less boring than a beep() without an external sound file.

import javax.sound.sampled.*;

public class SoundUtils {

  public static float SAMPLE_RATE = 8000f;

  public static void tone(int hz, int msecs) 
     throws LineUnavailableException 
  {
     tone(hz, msecs, 1.0);
  }

  public static void tone(int hz, int msecs, double vol)
      throws LineUnavailableException 
  {
    byte[] buf = new byte[1];
    AudioFormat af = 
        new AudioFormat(
            SAMPLE_RATE, // sampleRate
            8,           // sampleSizeInBits
            1,           // channels
            true,        // signed
            false);      // bigEndian
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();
    for (int i=0; i < msecs*8; i++) {
      double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
      buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
      sdl.write(buf,0,1);
    }
    sdl.drain();
    sdl.stop();
    sdl.close();
  }
  
  public static void main(String[] args) throws Exception {
    SoundUtils.tone(1000,100);
    Thread.sleep(1000);
    SoundUtils.tone(100,1000);
    Thread.sleep(1000);
    SoundUtils.tone(5000,100);
    Thread.sleep(1000);
    SoundUtils.tone(400,500);
    Thread.sleep(1000);
    SoundUtils.tone(400,500, 0.2);

  }
}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
RealHowTo
  • 34,977
  • 11
  • 70
  • 85
8

The applet route should be fine (and is very straightforward). To avoid creating an Applet instance you can use the static newAudioClip method, and then call play() on the AudioClip created.

URL url = getClass().getResource("/foo/bar/sound.wav");
AudioClip clip = Applet.newAudioClip(url);
clip.play();

Here, the sound.wav file is bundled in the jar file in the foo/bar package that you create. A fully functional class (where the wav file is in the sounds package) would look like this:

package sounds;

import java.applet.Applet;
import java.applet.AudioClip;

public class PlaySound {

    public void PlayBeep() {        
        AudioClip clip = Applet.newAudioClip(getClass().getResource("/sounds/beep3.wav"));
        clip.play();
    }
}

Here, the path is given as /sounds/ because when you extract the jar, you'll see that the wav file is located in the first folder in the jar, which is sounds.

Nav
  • 19,885
  • 27
  • 92
  • 135
Adamski
  • 54,009
  • 15
  • 113
  • 152
6

You can take a look at the beep method within the Toolkit class, as shown here

npinti
  • 51,780
  • 5
  • 72
  • 96
2

If you want to use the sound package to play an arbitrary sound file, you can use the javax.sound.sampled package. Here is the code that will play a sound file:

private void playSound(File f) {
    Runnable r = new Runnable() {
        private File f;

        public void run() {
            playSoundInternal(this.f);
        }

        public Runnable setFile(File f) {
            this.f = f;
            return this;
        }
    }.setFile(f);

    new Thread(r).start();
}

private void playSoundInternal(File f) {
    try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(f);
        try {
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            try {
                clip.start();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                clip.drain();
            } finally {
                clip.close();
            }
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        } finally {
            audioInputStream.close();
        }
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Erick Robertson
  • 32,125
  • 13
  • 69
  • 98