Search code examples
javajavasound

Adding audio to these wave formulas


I've written out these formulas that I believe should successfully generate the appropriate wave patterns. How could I integrate this with the java sound library to create test tones for each?

import java.lang.Math;

public class SoundWaves 
{
    int WAV_MULTI = 25;
    int amplitude;
    double frequency;
    int time;
    double sineWave;
    double sawWave;
    double squareWave;

    SoundWave ( int a, int f, int t)
    {
    }

    double makeSineWave ( int a,  int f, int t)
    {
        sineWave = a * Math.sin(2*PI*f*t); //passing amplitude frequency and time
        return sineWave;
    }

    double makeSawTooth (int a, int f, int t)
    {
        for ( int i = 1; i < WAV_MULTI; i++)
        {
            sawWave = sawWave + (Math.sin((2*PI*f*(i*t)/i); 
        }   
        return sawWave;
    }

    double makeSquareWave (int a, int f, int t)
        {
            for ( int i = 1; i < WAV_MULTI; i++)
            {
            if ( i%2 != 0 )
            squareWave = squareWave + (Math.sin((2*PI*f* (i*t)/i);  
            }   
            return squareWave;
        }
}

Solution

  • I did it by making a class that implements a TargetDataLine. Most of the methods to be overridden can be ignored. The data is fed to a SourceDataLine from the TargetDataLine.read() method. Your formulas would be consulted from the TargetDataLine to fill the data buffer that gets passed to the SDL.

    I'm assuming you already know about converting the audio values to PCM data, in the appropriate byte format.

    I used a wave table, and used formulas to generate the data in the wave tables, but your formulas should be fine. Just have to get them to map to the number of bits resolution (16-bit?) and fps rate (44100 Hz?).