Welcome to my blog, hope you enjoy reading
RSS

Monday 8 July 2013

Java beep sound example

Java beep sound example

There are different ways to generate a beep sound in java. The general basic way to generate is to use java.awt.Toolkit class which has a default method to generate the beep sound. The other implementation is also shown below on how to generate beep sound in java.


package com.javanotes2all.java.sound;

import java.awt.Toolkit;  
import javax.sound.sampled.AudioFormat;  
import javax.sound.sampled.AudioSystem;  
import javax.sound.sampled.LineUnavailableException;  
import javax.sound.sampled.SourceDataLine;  
public class Beep {  
     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 {  
          // Normal Beep sound  
          Toolkit.getDefaultToolkit().beep();  
          Beep.tone(1000, 100);  
          Thread.sleep(1000);  
          Beep.tone(100, 1000);  
          Thread.sleep(1000);  
          Beep.tone(5000, 100);  
          Thread.sleep(1000);  
          Beep.tone(400, 500);  
          Thread.sleep(1000);  
          Beep.tone(400, 500, 0.2);  
     }  
}  

0 comments: