Click here to Skip to main content
15,609,235 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

 * @dev :   devpar
 * @date :   03-May-2021

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

    public static void main(String[] args) throws Exception {

What I have tried:

I would like to understand how the tone method inside sound class is working.
Most of the things goes above from my head and could not understand the source.

link for the above source
Updated 3-May-21 21:29pm

1 solution

Share this answer
Udesh-Ranjan 5-May-21 19:26pm    
thanks Richard its difficult to understand with mathematical perspective.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900