pitch_shifting.py
1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pyaudio
import numpy as np
# Create an instance of the PyAudio class
audio = pyaudio.PyAudio()
# Define the desired pitch shift factor
pitch_shift_factor = 1.5 # Increase by 50%
# Choose the desired input and output devices
input_device_index = 1
output_device_index = 1
# Open input stream
input_stream = audio.open(input_device_index=input_device_index, format=pyaudio.paFloat32,
channels=1, rate=44100, input=True, frames_per_buffer=1024)
# Open output stream
output_stream = audio.open(output_device_index=output_device_index, format=pyaudio.paFloat32,
channels=2, rate=int(44100 * pitch_shift_factor), output=True)
# Read input audio and apply pitch shift
frames = []
while True:
data = input_stream.read(1024)
frames.append(data)
# Adjust pitch by changing sample rate
if len(frames) >= 1024:
audio_data = b''.join(frames)
audio_array = np.frombuffer(audio_data, dtype=np.float32)
# Resample the audio array to change the pitch
resampled_array = np.resize(audio_array, int(len(audio_array) / pitch_shift_factor))
# Convert the resampled array back to bytes
resampled_data = resampled_array.astype(np.float32).tobytes()
# Play the resampled audio
output_stream.write(resampled_data)
frames = []
# Stop and close the streams
input_stream.stop_stream()
input_stream.close()
output_stream.stop_stream()
output_stream.close()
# Terminate PyAudio
audio.terminate()