I was experimenting with producing beep using Java. I found this answer on SO.
I am using the code from that answer to produce beeps. The code is:
import javax.sound.sampled.*;
public class Sound
{
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,8,1,true,false);
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 {
Sound.tone(15000,1000);
}
}
In the main
method, I use Sound.tone(15000,1000);
to produce a sound of frequency 15000 Hz to play for 1000 ms
But, I can hear the sound if I change it to :
Sound.tone(1,1000);
, .Sound.tone(19999,1000);
Scientifically, this is not possible.
- In the first case, the sound should be infrasonic, and I should not be able to perceive it.
- In the second case, I should still not be able to hear the sound, because as we age, the hearing ability tends to decrease, and a person of about my age should only be able to hear a sound of approximately 16000 Hz.
Furthermore, I cannot hear:
Sound.tone(0,1000);
(somewhat as expected)Sound.tone(20000,1000);
So, How can I produce sounds of some specific frequencies?
I searched on the internet, but could not find anything regarding it.
The answers given before this edit explain why it occurs, but do not give the answer I want.
Sound.tone(10,1000);
, which should have been infrasonic. – ObvoluteSound.tone(1,1000);
, andSound.tone(19999,1000);
. I cannot hearSound.tone(0,1000);
(as expected) and alsoSound.tone(20000,1000);
– ObvoluteSound.tone(1, 1000)
is abnormal. – Obvolute