Skip to content

Instantly share code, notes, and snippets.

@diegovgsilva95
Created September 17, 2021 03:59
Show Gist options
  • Select an option

  • Save diegovgsilva95/ec60610fa964ad15eda77019bcd58dab to your computer and use it in GitHub Desktop.

Select an option

Save diegovgsilva95/ec60610fa964ad15eda77019bcd58dab to your computer and use it in GitHub Desktop.
Algorithm for phase adjustment between waves with two different frequencies
/**
* @protected {number} lastFrequency => In hertz, initialized as 0
* @protected {number} sampleRate => Audio output sample rate (e.g.: 8000 for 8KHz, 16000 for 16KHz, 44100 for 44.1KHz, 48000 for 48KHz and so on)
* @protected {number} frame => Current accumulative sample index
* @protected {number} offset => Accumulative phase, initialized as 0
*
* @param {number} frequency in hertz
*
* @returns {number} sample (-1 <= sample <= 1)
*/
const PI2 = Math.PI * 2;
let theta_A = (PI2 * frequency * frame / sampleRate) % PI2;
if(frequency != lastFrequency){
let theta_B = (PI2 * lastFrequency * frame / sampleRate) % PI2;
let cycle_A = theta_A / PI2;
let cycle_B = theta_B / PI2;
offset = (offset + (cycle_A - cycle_B) * PI2) % PI2;
}
let sample = Math.sin(theta_A - offset);
lastFrequency = frequency;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment