import soundfile as sf
import numpy as np
import sys
import pyaudio
from pyaec import Aec
import time
frame_size = 160
filter_length = 1600
sample_rate = 16000
aec = Aec(frame_size, filter_length, sample_rate, True)
song_path, out_path, echo_cancellation = sys.argv[1], sys.argv[2], sys.argv[3]
song_samples, _ = sf.read(song_path, dtype="int16")
p = pyaudio.PyAudio()
output_frames = []
input_stream = p.open(
format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
input=True,
frames_per_buffer=frame_size,
)
output_stream = p.open(
format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
output=True,
frames_per_buffer=frame_size,
)
def process_audio(duration=10):
global song_samples
start_time = time.time()
while len(song_samples) > frame_size and (time.time() - start_time) < duration:
in_samples = np.frombuffer(input_stream.read(frame_size), dtype="int16")
song_frame = song_samples[:frame_size]
song_samples = song_samples[
frame_size:
]
if echo_cancellation.lower() == "on":
processed_frame = aec.cancel_echo(in_samples, song_frame)
else:
processed_frame = (
in_samples )
output_frames.append(processed_frame)
output_stream.write(song_frame.tobytes())
output = np.concatenate(output_frames, axis=0)
output = output.astype(np.int16)
sf.write(out_path, output, sample_rate)
print(f"Created {out_path}")
process_audio(duration=10)
input_stream.stop_stream()
input_stream.close()
output_stream.stop_stream()
output_stream.close()
p.terminate()