I'm trying to make a simple game with an engine noise that goes up and down when player accelerates/decelerates.
From posts on SO I've got this little example...
public static final int SAMPLE_RATE = 16 * 1024; // ~16KHz
public void playNoise() throws Exception {
final AudioFormat af = new AudioFormat(Note.SAMPLE_RATE, 8, 1, true, true);
SourceDataLine line = AudioSystem.getSourceDataLine(af);
line.open(af, SAMPLE_RATE);
line.start();
byte[] engineNote = makeEngineNote();
line.write(engineNote, 0, engineNote.length);
line.drain();
line.close();
}
private byte[] makeEngineNote() {
// Create a kind-of-sin-wave-with-interference
byte[] b = new byte[SAMPLE_RATE];
...
}
Now I want to make the pitch fluctuate to mimic acceleration/deceleration. I was wondering about looping the above code (the write()
) but I'm not sure how to change the wavelength on the fly. I can't imagine re-generating the wav each time is the most desirable approach. I could create multiple wav's with different wavelengths but this wouldn't give a smooth transition.
Any help/links would be appreciated.
EDIT
The question isn't specifically about making an engine noise, the makeEngineNote()
method is sufficient for my needs. The question is about adjusting the pitch without generating the wav each time.
I've found a way, not sure how practical it is though.
I can copy the original wav, removing every n
th byte. This gives the effect of the pitch increasing. n
can then be derived from some variable which represents the engines throttle.
To make this less intensive I keep the wav as small as possible. Code basically looks a little like this...
int n = ...; // Inverse of throttle; as n gets bigger sound gets lower.
while (running) {
byte[] b = removeEveryNthByte(engineNote, n);
line.write(b, 0, b.length);
}
Just need to see if caching will be of use.