Skip to content

Instantly share code, notes, and snippets.

@mmontag
Last active March 15, 2020 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmontag/6f68d6e04c95869e691f5ba0aeb8b007 to your computer and use it in GitHub Desktop.
Save mmontag/6f68d6e04c95869e691f5ba0aeb8b007 to your computer and use it in GitHub Desktop.
NES noise channel
class NoiseVoice {
// Invariant stuff
static const int fs = 44100; // sample rate
static const int ntsc = 3579545; // ntsc clock rate
static const int buffer[32767]; // fill randomly with 0s and 1s
static const int periods[] = { 4068, 2034, 1016, 762, ... }; // from nesdev wiki
int loop = 93; // or 32767 :)
float timestep; // can be a fraction less than 1
float ctr; // accumulates timesteps
// Per-voice stuff
void noteOn(int noteNum) {
const int period = periods[noteNum % 16]; // select a period based on MIDI note number
timestep = ntsc / (fs * 2 * period);
ctr = 0;
}
// Per-voice sample rendering
int getNextSample() {
ctr = (ctr + timestep);
if (ctr >= loop) ctr -= loop;
return buffer[(int)ctr]; // output will be 0 or 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment