-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
95 lines (72 loc) · 2.5 KB
/
app.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
from flask import Flask, request, render_template, Response, stream_with_context
# AUDIO imports
import pyaudio
import struct
import numpy as np
from scipy.fftpack import fft
app = Flask(__name__)
# AUDIO: constants
CHUNK = 1024 * 2 # samples per frame
FORMAT = pyaudio.paInt16 # audio format (bytes per sample?)
CHANNELS = 1 # single channel for microphone
RATE = 44100 # samples per second
DEVICE_INDEX = 1
p = pyaudio.PyAudio()
# print devices
info = p.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
print("i = " + str(i) + ". Input Device id = ", i, " - ", p.get_device_info_by_host_api_device_index(0, i).get('name'))
print("\n - - -")
print("SELECTED Input Device id ", DEVICE_INDEX, " - ", p.get_device_info_by_host_api_device_index(0, DEVICE_INDEX).get('name'))
print("\n - - -")
# x = np.arange(0, 2 * CHUNK, 1)
# create an evenly divided array for the freq spectrum. 0-44100
xf = np.linspace(0, RATE, CHUNK)
# stream object to get data from microphone
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
#input_device_index=DEVICE_INDEX,
frames_per_buffer=CHUNK
)
print('stream started')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/wavefeed')
def wavefeed():
return Response(get_sound_wave(), mimetype="text/plain")
@app.route('/spectrumfeed')
def spectrumfeed():
return Response(get_sound_freq(), mimetype="text/plain")
def get_sound_wave():
# get sound data
# binary data
data = stream.read(CHUNK)
# convert data to integers, make np array, then offset it by 127
data_int = struct.unpack(str(2 * CHUNK) + 'B', data)
# create np array and offset by 128
data_np = np.array(data_int, dtype='b')[::2] + 128
x = data_np.tolist()
yield str(x)
def get_sound_freq():
# get sound data
# binary data
data = stream.read(CHUNK)
# convert data to integers, make np array, then offset it by 127
data_int = struct.unpack(str(2 * CHUNK) + 'B', data)
# create np array and offset by 128
#data_np = np.array(data_int, dtype='b')[::2] + 128
yf = fft(data_int)
a = yf[0:CHUNK]
a1 = np.abs(a)
b = (128 * CHUNK)
spectrum_data = a1 / b
result = spectrum_data[::4]
x = result.tolist()
yield str(x)