Question

I was testing out this code I found for a little audio app in android and I'm a bit stuck on something.

short samples[] = new short[buffsize];
int amp = 32767;
double twopi = 2*Math.PI;
double fr = 262.f;
double ph = 0.0;

while(isRunning)
{
    fr = 262 + 262*sliderval;

    for(int i=0; i < buffsize; i++)
    {
        samples[i] = (short) (amp*Math.sin(ph));
        ph += twopi*fr/sr;
    }
    audioTrack.write(samples, 0, buffsize);
}

I know that this loop works to synthesize the sound, but I don't know what the "ph" parameter is and how it fits into the math to generate the sine wave. Could someone please explain it to me if they know what it is?

Was it helpful?

Solution 2

A sine wave is derived from this function:

y(t) = Amplitude * Sin( 2* PI * Frequency * SAMPLE_TIME)

This line of code:

samples[i] = (short) (amp * Math.sin(ph));

is essentially the function above. On the first execution of the for-loop, ph is zero, hence, the computation works. ph essentially is the angle part given to the function above. Next, ph takes the value:

ph += twopi * fr/sr;

Here, fr / sr is Frequency / Sample_Rate. Also, note that:

SAMPLE_TIME = 1 / SAMPLE_RATE

OTHER TIPS

It's the phase of the sine wave. The initial value is 0 so the wave's first sample is 0. Then for each sample it is incremented so the waveform has the specified frequency.

Looks more a mathematical question anyway...

More info on phases should you need: Wikipedia - Phase(waves)

In the code above, ph is a Phase Accumulator.

The following two relationships might help with understanding what is going on:

  1. Frequency is the rate of change of phase with respect to time.
  2. Sin(x) = Sin(x + N * 2 * PI) for all integer values of N

As each time round the loop, a phase difference between samples is added onto the phase accumulator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top