This old thread seems to indicate that pydub's AudioSegment._data
can be used to somehow calculate the pitch of a sound; unfortunately, it seems to be done using a method assigned to the undisclosed Mpm
class. That said, however, if pitch data can be extracted from AudioSegment._data
, is there a way then to use pydub to shift an AudioSegment
's pitch up or down? If not, is there another library for Python 2.7 that can?
Asked
Active
Viewed 4,469 times
3
3 Answers
6
Yes. After spending about 6 hours today working on this problem I got it to work. Try this. Note I initially had an issue with a popping noise at the end, but that was due to the peculiarities of my particular file and not any other reason.
import os
from pydub import AudioSegment
from pydub.playback import play
cwd = os.getcwd()
wavepath = cwd+"\\Soundfiles\\CritHit.WAV"
sound = AudioSegment.from_file(wavepath, format="wav")
play(sound)
print(sound.frame_rate)
# shift the pitch down by half an octave (speed will decrease proportionally)
octaves = -0.5
new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
lowpitch_sound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
#Play pitch changed sound
play(lowpitch_sound)

Zaorish9
- 103
- 2
- 10
-
people using Windows, where developer suggested using simpleaudio library, play function does not support using weird sample rates so it won't work. You can try deleting the if block from the source and then installing. – NONONONONO May 20 '20 at 23:32
0
for mono sound,you can use this code
from pydub import AudioSegment
import numpy as np
import librosa
def pitch_shift(sound, n_steps):
y = np.frombuffer(sound._data, dtype=np.int16).astype(np.float32)/2**15
y = librosa.effects.pitch_shift(y, sound.frame_rate, n_steps=n_steps)
a = AudioSegment(np.array(y * (1<<15), dtype=np.int16).tobytes(), frame_rate = sound.frame_rate, sample_width=2, channels = 1)
return a
sound = AudioSegment.from_mp3("ori.mp3")
sound = pitch_shift(sound, 4)
sound.export("shift.mp3")

partida
- 501
- 4
- 20
0
On Windows it works with pydub and simpleaudio using this code:
from pydub import AudioSegment
from pydub.playback import play
sound = AudioSegment.from_file('samples/piano_c2.wav', format="wav")
#play(sound)
octaves = 1.5
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)
play(hipitch_sound)
See https://batulaiko.medium.com/how-to-pitch-shift-in-python-c59b53a84b6d