How to Pitch Shift in Python

Batu YILDIRIM
2 min readFeb 3, 2021

Pitch Shift is a method for making audio thinner or thicker. It is about changing octave.

Here is the method for pitch shift easily in Python.

Firstly, install “pydub” library. Pydub helps us to manipulate audio with an simple and easy high level interface.

pip install pydub

After installation, import AudioSegment module and load sound file.

from pydub import AudioSegment
filename = 'input.wav'
sound = AudioSegment.from_file(filename, format="wav")
#For every sound type, I am using the method under below.
#sound = AudioSegment.from_file(filename, format=filename[-3:])

Set the octave which determine the audio will be thicker or thinner.

octaves = 0.5 # For decreasing, octave can be -0.5, -2 etc.new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))

Sample rate is changed and audio become very weird. So, to fix this:

hipitch_sound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})

Now, For converting sample rate to standard audio CD sample rate, which is 44.1K:

hipitch_sound = hipitch_sound.set_frame_rate(44100)

All in all, export the pitched audio file via pydub:

hipitch_sound.export("out.wav", format="wav")

There is the full of Code example:

from pydub import AudioSegment
from numpy.random import uniform
filename = 'in.wav'
sound = AudioSegment.from_file(filename, format=filename[-3:])

octaves = 0.5
for octaves in np.linspace(-1,1,21):
new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
hipitch_sound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
hipitch_sound = hipitch_sound.set_frame_rate(44100)
#export / save pitch changed sound
hipitch_sound.export(f"octave_{octaves}.wav", format="wav")

Thanks for reading. I hope it will be helpful to you.

--

--

Batu YILDIRIM

Electric Electronic Engineer. Skilled in working on analog design, PCB design, C++ and Python also starts to learn IoT and machine learning applications.