make_echo.py
1.07 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
import sys
import numpy as np
import pyaudio
RECORD_SECONDS = 5
CHUNK = 128
RATE = 44100
DELAY = 0.1 # Delay time in seconds
GAIN = 1 # Echo gain (0 to 1)
# Create buffer for delayed audio data
buffer_size = int(RATE * DELAY)
buffer = np.zeros(buffer_size, dtype=np.int16)
def add_echo(in_data, frame_count, time_info, status_flags):
global buffer
data = np.frombuffer(in_data, dtype=np.int16)
output = data + GAIN * buffer[:len(data)]
buffer = np.roll(buffer, len(data))
buffer[-len(data):] = data
return (output.astype(np.int16).tobytes(), pyaudio.paContinue)
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2),
channels=1 if sys.platform == 'darwin' else 2,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK,
stream_callback=add_echo
)
print('* recording')
stream.start_stream()
while stream.is_active():
# Do other processing here if necessary
pass
stream.stop_stream()
stream.close()
p.terminate()