Skip to content

Instantly share code, notes, and snippets.

@JA1TYE
Last active December 18, 2022 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JA1TYE/b7ea9917214c661d7a4eced185a79338 to your computer and use it in GitHub Desktop.
Save JA1TYE/b7ea9917214c661d7a4eced185a79338 to your computer and use it in GitHub Desktop.
Resample type Pitch Shift Effect
from pydub import AudioSegment
import numpy as np
from pydub.playback import play
buflen = 2000
crossfadelen = 100
rate = 2.0
buf = np.zeros(buflen)
sound = AudioSegment.from_file("input.wav", "wav")
samples = np.array(sound.get_array_of_samples())
sample = samples[::sound.channels]
rpf = 0
rp1 = 0
rp2 = 0
wp = 0
result = np.zeros(len(sample))
gain1 = 1.0#gain for buffer line 1
gain2 = 0.0#gain for buffer line 2
#Processing loop
for i in range(len(sample)):
buf[wp] = sample[i] #Write sample to the ring buffer
out1 = buf[rp1] #Read sample from the ring buffer (pointer 1)
out2 = buf[rp2] #Read sample from the ring buffer (pointer 2)
#Calculate distance between write pointer and read pointer
posdiff1 = wp - rp1
posdiff2 = wp - rp2
if rate <= 1.0:
posdiff1 = -1.0 * posdiff1
posdiff2 = -1.0 * posdiff2
#Crossfade
if 0 <= posdiff1 <= crossfadelen:
sgain = np.sin(abs(posdiff1) * np.pi * 0.5/crossfadelen)
cgain = np.cos(abs(posdiff1) * np.pi * 0.5/crossfadelen)
gain1 = sgain * sgain
gain2 = cgain * cgain
if 0 <= posdiff2 <= crossfadelen:
sgain = np.sin(abs(posdiff2) * np.pi * 0.5/crossfadelen)
cgain = np.cos(abs(posdiff2) * np.pi * 0.5/crossfadelen)
gain1 = cgain * cgain
gain2 = sgain * sgain
result[i] = round(out1*gain1 + out2*gain2)
#Update write pointer and read pointer
wp = (wp + 1) % buflen
rpf = rpf + rate
rp1 = int(round(rpf)) % buflen
rp2 = (rp1 + buflen//2) % buflen
test = AudioSegment(result.real.astype("int16").tobytes(), sample_width=sound.sample_width, frame_rate=sound.frame_rate, channels = 1)
test.export("output.wav", format="wav")
play(test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment