Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a sound (alert) in a java application? [duplicate]

Tags:

java

audio

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!

like image 343
Krithika Avatar asked Sep 23 '10 16:09

Krithika


People also ask

How do you play a sound clip in Java?

Following steps are to be followed to play a clip object. getAudioInputStream(File file). AudioInputStream converts an audio file into stream. Get a clip reference object from AudioSystem. Stream an audio input stream from which audio data will be read into the clip by using open() method of Clip interface.

Can you play sounds in Java?

Java API Support for MP3 Format. Currently, both Clip and SourceDataLine can play audio files in AIFC, AIFF, AU, SND, and WAV formats. We can check the supported audio format using AudioSystem: Type[] list = AudioSystem.


2 Answers

If you just want a beep or quick alert try

Toolkit.getDefaultToolkit().beep(); 
like image 192
Sean Avatar answered Sep 18 '22 13:09

Sean


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

More sound experiments here : Produce special sound effect

like image 28
RealHowTo Avatar answered Sep 19 '22 13:09

RealHowTo