Lord Rixuel
Lord Rixuel

Reputation: 1233

How to play a sound other than beep in Java?

So currently, this is the "beep" (not really beep on some OS) sound in Java:

Toolkit.getDefaultToolkit().beep();

But the code uses the "beep"/alert sound of my computer...

Is there a way to replace it?

Upvotes: 5

Views: 5867

Answers (2)

OlaB
OlaB

Reputation: 186

Just create a function as such, and call it wherever you please such as a button click or listener.

public void alert() {

    try{

        InputStream inputStream = getClass().getResourceAsStream("/sounds/sms.wav"); //Note this is path to whatever wav file you want
            AudioStream audioStream = new AudioStream(inputStream);
            AudioPlayer.player.start(audioStream);
        }
    catch (IOException e) {
       // Whatever exception you please;
    }
       // return inputStream;

}

Also Note: Audiostream Class is proprietary to Java, and if its a lengthy sound byte and need to stop it at anytime, you can call AudioPlayer.player.stop(audioStream) anywhere either with a timer, thread interrupt or button click.

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172428

There is a interesting code here which I found and which uses a different sound other than beep:

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);

  }
}

Upvotes: 9

Related Questions