3

Problem

I'm trying to figure this out for a while to no avail - how to continuously change the pitch of a note between two frequencies.

I'm generating the audio signal with a function similar to this:

double SineGenerator(double time, double frequency)
{
    return Math.Sin(frequency * time * 2 * Math.PI);
}

While I manage time manually outside of this function, like so:

time += 1.0 / sampleRate;
double sample = SineGenerator(time, frequency);

And the obvious solution of linearly interpolating the frequency parameter over the desired amount of samples does not work as expected. The sound wave gets filled with pops and clicks when doing this.

How must I implement this instead?

Solution (Edit)

Thanks to geofftnzless, this was surprisingly easy to solve. I have switched to using this generator now:

double SineGenerator(ref double time, double frequency, int sampleRate)
{
    return Math.Sin(time += (frequency * 2 * Math.PI) / sampleRate);
}

Which takes care of incrementing time internally.

Using this generator interpolating frequency works smoothly and with not audible problems. Thanks!

David Gouveia
  • 548
  • 5
  • 17

1 Answers1

4

Instead of multiplying frequency by time, use frequency to increment time by the appropriate amount. That way time is continuous and you wont get jumps.

geofftnz
  • 9,954
  • 2
  • 42
  • 50
  • I.e. `Sin(time + frequency)` (which I believe would normally be called a *phase*, not a frequency)? In that case, what's the "appropriate amount"? I need control over the pitch of each note, and using the sine wave function above, the frequency parameter lets me do that in a straightforward way. I have no clue how I would be able to control the sound's frequency by changing its phase (or if that's even possible). – David Gouveia Dec 19 '11 at 20:44
  • No, I mean keep track of the `time` for each generator, and go `time += (2.0 * Math.PI * frequency) / (samples_per_second)` (I think that's right) – geofftnz Dec 19 '11 at 20:50
  • Roger, I'll give that a try in a bit. – David Gouveia Dec 19 '11 at 21:02
  • The downside is having to keep state, but I can't see any other way. – geofftnz Dec 19 '11 at 21:36
  • That won't be a problem. Will give a try now and post an update as soon as I have some results. – David Gouveia Dec 19 '11 at 21:38