I want to be able to change the pitch in order to play diferent notes
Ah, well pitch shifting is pretty simple. You need to change the rate of the sound. For example, if you've got the wave:
0, 1, 0, -1, 0, 1, 0, -1
You can cut the speed in half by playing each sample twice:
0, 0, 1, 1, 0, 0, -1, -1, 0, 0, 1, 1, 0, 0, -1, -1,
Although stretching it like this can result in quantization errors... a fancy name for the "stair-step" aliasing effects that you get when scaling an image. The same thing happens with audio and it's usually best to interpolate the wave when you stretch it:
0, 0.5, 1, 0.5, 0, -0.5, -1, -0.5, 0, 0.5, 1, 0.5, 0, -0.5, -1, -0.5
Anyway, by doubling the length of the wave, I have cut the frequency in half. This is equivalent to moving down one octave, aka 12 semitones. Doubling the frequency is going up an octave.
Here's some code that can shift the pitch of a sample:
int sample[] = {0, 1, 0, -1, 0, 1, 0, -1};
int sampleLength = 8;
float semitoneShift = -12; // one octave down
float samplePosition = 0;
float sampleSpeed = pow(2.0f, (float) semitoneShift / 12.0f);
while (samplePosition < sampleLength - 1) {
int firstSampleIndex = (int) samplePosition;
int secondSampleIndex = firstSampleIndex + 1;
float secondScale = samplePosition - firstSampleIndex;
float firstScale = 1.0f - secondScale;
out[i++] = sample[firstSampleIndex] * firstScale +
sample[secondSampleIndex] * secondScale;
samplePosition += sampleSpeed;
}
This should do the same thing as I demonstrated above, but it will work with any pitch shift, up or down. (I think... I haven't compiled it as-is)
All that's left is to figure out the original pitch of your sample. I don't have any good algorithms for that off the top of my head, but basically a wave that looks like it roughly repeats 440 times per second is known as
A440. If your sampling rate is 44100 samples per second (the standard) then a wave with a pitch of middle A will roughly repeat every 100 samples.
Ugh, the word "sample" is overloaded to refer to the entire wave, and to the values of the wave recorded at various points in time.