Resample type Pitch Shift Effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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