# Pitch/Time Shifting of a PCM byte array

I am searching for a universal algorithm that shifts pitch and time while keeping the sample rate. (I am trying to program a sound generator (sine, triangle...) as an exercise)

I just want to squeeze the samples of the sound together so it appears to be shorter and pitched higher.

It's easy if you want to speed it up with a nice number like 2 (leave out every second sample) but what if you want to speed it up by 2.5?

Can someone name an algorithm for this? (preferably in C++, but other languages are also fine)

(I spent the last 30 minutes writing an algorithm that computes averages of decimals of a number (Like the average of every 2.5 numbers). Then I realized it's totally useless so please help)

Does this approach make sense?: (Will be adding pseudocode shortly)

``````N is the amount of the pitch
Divide the index of every sample of the sound by N (2/2.8=0.71; 3/2.5=1.07)
For every whole number, compute the distances to the next samples (0.29; 0.07)
Value portions of distance (1-(0.29/0.36)=19%; 1-(0.07/0.36)=81%
New number (New Sample = (19%*SampleA + 81%*SampleB)/2)
``````

Code:

``````byte[] input;
double f = factor;
byte[] output = new byte[ceil(input / f)];
output = input
for(int i = 1; i < output.length) {
output[i] = (input[floor(i*factor)] + input[ceil(i*factor)]) / 2;
}
``````
• Basically, you have to re-plot the sound wave over a shorter period of time, and recompute the samples. However, if you don't want it to sound like Mickey Mouse, things get a little more complicated. See blogs.zynaptiq.com/bernsee/formants-pitch-shifting – Robert Harvey Jul 3 '16 at 6:30
• Thanks, I'll try the replotting. I want the sound higher and shorter, and I need the Mickey Mouse effect. I just couldn't find an algorithm online anywhere, there where just pitch/time shifting code samples where only pitch OR time changed :( – KeksArmee Jul 3 '16 at 10:54
• look up "audio resampling" – Display Name Jul 3 '16 at 11:04
• As previous commenter said, look up 'Audio Resampling'. Also, maybe buy the book called 'The Art of Digital Audio' or similar. Basically, what you are doing is linear interpolation, should work. But resampling at a much higher rate should allow you to pick samples (from the denser set) close to the sample points you need for e.g 2.5 speedup. If you like maths, read this practical classic: amazon.com/Fourier-Transform-Its-Applications/dp/0073039381 – Erik Alapää Jul 22 '16 at 6:42
• this should migrate over to the dsp.se site. – robert bristow-johnson Jul 22 '16 at 11:02