-
Notifications
You must be signed in to change notification settings - Fork 0
/
capture.py
executable file
·99 lines (87 loc) · 2.99 KB
/
capture.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
99
#!/usr/bin/env python3
import argparse
import itertools
import sys
import colorama
import pyaudio
import numpy
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100*4
CHUNK = 1024*4
BUFFERS = 5
RECORD_SECONDS = 5
def mkColor(color):
def wrapcolor(*args, **kwargs):
sep = kwargs.get("sep", " ")
text = sep.join(map(str, args))
return color + text + colorama.Fore.RESET
return wrapcolor
red = mkColor(colorama.Fore.RED)
green = mkColor(colorama.Fore.GREEN)
def track(options):
audio = pyaudio.PyAudio()
rate = options.sample_rate if options.sample_rate else RATE
buffers = options.buffers if options.buffers else BUFFERS
chunk = options.buffer_size if options.buffer_size else CHUNK
stream = audio.open(format=pyaudio.paInt16,
channels=CHANNELS,
rate=rate,
input=True,
input_device_index=options.input_device_index,
frames_per_buffer=chunk)
for display in itertools.cycle(range(buffers)):
data = stream.read(chunk)
data = numpy.fromstring(data, dtype=numpy.int16)
if not display:
a = data
else:
a = numpy.append(a, data)
if (display + 1) % buffers == 0:
delta_t = (float(chunk)* buffers )/rate
a = a - numpy.mean(a)
fft = numpy.fft.fft(a)
fft[chunk//2:] = 0 # prevents alias from being detected
afft = numpy.abs(fft)
amax = numpy.argmax(afft)
print("%.3f %.3f (%.3f-%.3f)" % (amax/delta_t,
numpy.max(afft),
(amax - 1)/(2*delta_t),
(amax+1)/(2*delta_t)))
stream.stop_stream()
stream.close()
audio.terminate()
def list_devices():
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
device = p.get_device_info_by_index(i)
isInput = True if device["maxInputChannels"] else False
color = green if isInput else red
print(i, device["name"], "isInput:", color(isInput))
def device_info(options):
p = pyaudio.PyAudio()
for key, val in p.get_device_info_by_index(options.info).items():
print(key, val)
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument("--list", action="store_true",
help="list devices.")
parser.add_argument("--info", type=int,
help="get info on device with provided index.")
parser.add_argument("--input-device-index", type=int,
help="specify which device to use.")
parser.add_argument("--sample-rate", type=int,
help="specify the sample rate of the input device to use.")
parser.add_argument("--buffers", type=int,
help="number of buffers to use in fft.")
parser.add_argument("--buffer-size", type=int,
help="size of sampling buffer.")
options = parser.parse_args(args)
if options.list:
list_devices()
elif options.info != None:
device_info(options)
else:
track(options)
if __name__ == "__main__":
main(sys.argv[1:])