make_echo.py 1.07 KB



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()