-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkaraoke.py
98 lines (70 loc) · 2.13 KB
/
karaoke.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from doctest import OutputChecker
import pyaudio
import numpy as np
import wave, os
from datetime import detetime
from audioop import mul, add, bias
#brew install portaudio
#pip install pyaudio
INPUT_INDEX = 5
OUTPUT_INDEX = 3
OUTPUT_FILENAME = 'output/%s.wav' % (datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
os.makedirs('output', exist_ok = True)
CHUNK = 512
RATE = 48000
SAMPLE_WIDTH = 2
DELAY_INTERVAL = 15
DELAY_VOLUME_DECAY = 0.6
DELAY_N = 10
#delay sound
original_frames = []
index = 0
def add_delay(input):
global original_frames, index
original_frames.append(input)
output = input
if len(original_frames) > DELAY_INTERVAL:
for n_repeat in range(DELAY_N):
delay = original_frames[max(index - n_repeat * DELAY_INTERVAL, 0)]
delay = mul(delay, SAMPLE_WIDTH, DELAY_VOLUME_DECAY ** (n_repeat + 1))
output = add(output, delay, SAMPLE_WIDTH)
index += 1
return output
def start_stream():
#open devices
stream = pa.open(
format = pyaudio.paInt16,
channels=1,
rate = RATE,
frames_per_buffer = CHUNK,
input = True,
output = True,
input_device_index = INPUT_INDEX,
output_device_index = OUTPUT_INDEX
)
frames = []
while stream.is_active():
try:
input = stream.read(CHUNK, exception_on_overflow=False)
input = add_delay(input)
stream.write(input)
frames.append(input)
except KeyboardInterrupt:
break
except Exception as e:
print('[!] Unknown error!', e)
exit ()
total_frames = b''.join(frames)
with wave.open(Output_FILENAME, 'wb') as f:
f.setnchannels(1)
f.setsampwidth(pa.get_sample_size(pyaudio.paInt16))
f.setframerate(RATE)
f.writeframes(total_frames)
stream.stop_stream()
stream.close()
pa.terminate()
#main
pa = pyaudio.PyAudio()
for i in range(pa.get_device_count()):
print(pa.get_device_info_by_index(i))
start_stream()