Repository navigation
Expand file tree
/
Copy pathmain_two_channels.py
More file actions
370 lines (283 loc) · 14.2 KB
/
Copy pathmain_two_channels.py
File metadata and controls
370 lines (283 loc) · 14.2 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# data to import
import wave # read & write WAV files
import pyaudio # use Python to play and record audio
import numpy as np # library contains multidimensional array data structures
from scipy.io import wavfile # to read & write data to a variety of file formats -> in this case wavfile
import matplotlib.pyplot as plt # a collection of command style functions that make matplotlib work like MATLAB
from datetime import datetime
from datetime import date
import os
import argparse
import sys
import time
# influxdb_client -> to collect, store, process and visualize time series data
import influxdb_client, os, time
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
#print("Current date =", current_date)
today = date.today()
current_date = today.strftime("%y%m%d")
#print("Current Time =", current_time)
now = datetime.now()
current_time = now.strftime("%H%M%S")
#Setup
FORMAT = pyaudio.paInt16 # 16-bit resolution
CHANNELS = 2 # Choose number of Channels, 1 = mono, 2 = stereo L/R
RATE = 44100 # 44.1kHz sampling rate
CHUNK = 512 # 2^10 samples for buffer size
REFERENCE_FILENAME = "reference.wav"
# Initialize PyAudio
audio = pyaudio.PyAudio()
# Specify the name of the desired audio interface
#SelectedInterface = 'USB Audio CODEC '
SelectedInterface = 'USB Audio CODEC: - (hw:3,0)'
#SelectedInterface = 'MacBook Pro-Mikrofon'
def get_device_index_by_name(device_name):
p = pyaudio.PyAudio()
info = p.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
device_info = p.get_device_info_by_host_api_device_index(0, i)
if (device_info.get('maxInputChannels') > 0) and (device_info.get('name') == device_name):
return i # Return the device index if it matches the name
return None # Return None if no matching device is found
def Audio_fft(wav_file):
"""
Analyze audio frames by performing FFT and converting the magnitude to dB.
Parameters:
- audio_frames: list of byte strings, the audio frames to be analyzed
- sample_rate: int, the sampling rate of the audio (e.g., 44100)
Returns:
- positive_frequencies: numpy array, the positive frequency components
- positive_magnitude_db: numpy array, the magnitude in dB for the positive frequencies
"""
# Convert the recorded byte data to a numpy array
sample_rate, audio_data = wavfile.read(wav_file)
# Perform FFT (Fast Fourier Transform)
fft_data = np.fft.rfft(audio_data)
fft_magnitude = np.abs(fft_data) # Get the magnitude of the FFT
# Frequency axis (x-axis)
positive_frequencies = np.fft.rfftfreq(len(audio_data), 1.0 / sample_rate)
# Convert magnitude to dB (adding a small constant to avoid log(0))
positive_magnitude_db = 20 * np.log10(fft_magnitude + 1e-10)
return positive_frequencies, positive_magnitude_db
def moving_average(xdata, ydata, window_size):
smoothed_ydata = np.convolve(ydata, np.ones(window_size) / window_size, mode='valid')
smoothed_xdata = xdata[(window_size - 1) // 2 : -(window_size - 1) // 2]
return smoothed_xdata, smoothed_ydata
def record_sample(device_index, RECORD_SECONDS, OUTPUT_FILENAME):
# Start Recording
stream = audio.open(format=FORMAT, input_device_index = device_index, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
print(f"Recording for {RECORD_SECONDS} seconds")
audio_frames = []
total_frames = int(RATE / CHUNK * RECORD_SECONDS)
for _ in range(total_frames):
data = stream.read(CHUNK)
audio_frames.append(data)
print("Finished recording.")
# Stop Recording
stream.stop_stream()
stream.close()
# Save the recording as a WAV file
wavefile = wave.open(OUTPUT_FILENAME, 'wb')
wavefile.setnchannels(CHANNELS)
wavefile.setsampwidth(audio.get_sample_size(FORMAT))
wavefile.setframerate(RATE)
wavefile.writeframes(b''.join(audio_frames))
wavefile.close()
return b''.join(audio_frames) # Return recording in bytes
def split_audio(audio_data, sample_width, num_channels, part_duration, rate, base_filename):
part_length = int(rate * part_duration * num_channels * sample_width) # Number of bytes / part
num_parts = len(audio_data) // part_length
for i in range(num_parts):
part_data = audio_data[i * part_length: (i + 1) * part_length]
part_filename = f"{base_filename}_part_{i + 1}.wav"
# Save each part as a separate WAV file
part_wavefile = wave.open(part_filename, 'wb')
part_wavefile.setnchannels(num_channels)
part_wavefile.setsampwidth(sample_width)
part_wavefile.setframerate(rate)
part_wavefile.writeframes(part_data)
part_wavefile.close()
print(f"Saved part {i + 1} as {part_filename}")
def integrate_frequency_range(frequencies, magnitudes, freq_min, freq_max, is_db=False):
# Select frequencies within the desired range
freq_mask = (frequencies >= freq_min) & (frequencies <= freq_max)
# Extract corresponding magnitudes
selected_frequencies = frequencies[freq_mask]
selected_magnitudes = magnitudes[freq_mask]
# If the magnitudes are in dB, convert them to linear scale for integration
if is_db:
selected_magnitudes = 10 ** (selected_magnitudes / 20)
# Integrate by summing magnitudes
integrated_value = np.sum(selected_magnitudes)
return integrated_value
def plot_stereo_waveform(filename):
with wave.open(filename, 'rb') as wfs:
n_channels = wfs.getnchannels()
sample_width = wfs.getsampwidth()
frame_rate = wfs.getframerate()
n_frames = wfs.getnframes()
audio_data = wfs.readframes(n_frames)
# Convert to numpy array
audio_array = np.frombuffer(audio_data, dtype=np.int16)
audio_array = audio_array.reshape(-1, n_channels)
time_axis = np.linspace(0, len(audio_array) / frame_rate, num=len(audio_array))
plt.figure(figsize=(12, 6))
plt.plot(time_axis, audio_array[:, 0], label="Left Channel")
plt.plot(time_axis, audio_array[:, 1], label="Right Channel", alpha=0.7)
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.title("Stereo Audio Waveform")
plt.legend()
plt.grid()
plt.tight_layout()
plt.show()
def compare_fft(recorded_filename, reference_filename, rate, window_size = 17):
def extract_channels(data):
if data.ndim == 1:
return data, data # mono case: duplicate
return data[:, 0], data[:, 1] # stereo: left, right
# Read stereo audio
rate1, data1 = wavfile.read(recorded_filename)
rate2, data2 = wavfile.read(reference_filename)
assert rate1 == rate2, "Sampling rates must match"
left1, right1 = extract_channels(data1)
left2, right2 = extract_channels(data2)
# Force stereo format
if data1.ndim == 1:
data1 = np.column_stack([data1, data1])
if data2.ndim == 1:
data2 = np.column_stack([data2, data2])
channels = ['Left Channel', 'Right Channel']
integrated_differences = {}
for xmax, title, fname in [
(20000, "Spectrum up to 20 kHz", f"EntireSpectrum.png"),
(1000, "Spectrum up to 1 kHz", f"Spectrum1000.png"),
(200, "Spectrum up to 200 Hz", f"Spectrum200.png"),
]:
fig, ax = plt.subplots(1, CHANNELS,figsize=(16, 6))
for ch in [0, 1]:
sig1 = data1[:, ch]
sig2 = data2[:, ch]
# Compute FFT
fft1 = np.abs(np.fft.rfft(sig1))
fft2 = np.abs(np.fft.rfft(sig2))
freqs1 = np.fft.rfftfreq(len(sig1), 1 / rate1)
freqs2 = np.fft.rfftfreq(len(sig2), 1 / rate2)
if not np.allclose(freqs1, freqs2):
raise ValueError("Frequency bins of recorded and reference signals do not match.")
freqs = freqs1
# Convert to dB
def smooth(data, window_size=50): return np.convolve(data, np.ones(window_size)/window_size, mode='same')
db1 = 20 * np.log10(fft1 + 1e-10)
db2 = 20 * np.log10(fft2 + 1e-10)
# Moving average
def smooth(x, w): return np.convolve(x, np.ones(w)/w, mode='valid')
smoothed_freqs = freqs[(window_size - 1)//2: -(window_size - 1)//2 or None]
db1_smooth = smooth(db1, window_size)
db2_smooth = smooth(db2, window_size)
# Frequency difference and integration
db_diff = db1 - db2
integrated = np.sum(10**(db_diff[(freqs1 >= 20) & (freqs1 <= 1000)] / 20))
integrated_differences[channels[ch]] = integrated
# Plotting
ax[ch].plot(freqs, db1, label="Recorded")
ax[ch].plot(freqs, db2, label="Reference")
ax[ch].plot(smoothed_freqs, db1_smooth, '--', label="Recorded Smooth")
ax[ch].plot(smoothed_freqs, db2_smooth, '--', label="Reference Smooth")
ax[ch].set_title(f"Channel {ch}")
ax[ch].set_xlabel("Frequency (Hz)")
ax[ch].set_ylabel("Magnitude (dB)")
ax[ch].set_xlim(0, xmax)
ax[ch].grid(True)
ax[ch].legend()
fig.suptitle(f"{title}")
plt.tight_layout()
fig.savefig(fname)
plt.show()
#input("Press Enter to continue...")
return integrated_differences
def main():
parser = argparse.ArgumentParser(description="Choose Recording-Type")
parser.add_argument('--duration', type=float, required= True, help="Specify duration of record in sec.")
parser.add_argument('--split', action='store_true', help="If set, recording will be split into 0.5sec-parts")
parser.add_argument('--continuous', action='store_true', help="If set, record in intervals for long durations.")
parser.add_argument('--pushtodb', action='store_true', help="If set, integral value is pushed to influxdb.")
parser.add_argument('--total_time', type=float, required='--continuous' in sys.argv, help="Total time to record in hours.")
parser.add_argument('--interval', type=float, required='--continuous' in sys.argv, help="Intervals between recordings in seconds.")
args = parser.parse_args()
now = datetime.now()
current_date = now.strftime("%Y%m%d")
current_time = now.strftime("%H%M%S")
# Get the device index for the target interface
device_index = get_device_index_by_name(SelectedInterface)
if device_index is None:
print(f"Error: Your Interface '{SelectedInterface}' not found.")
else:
print(f"Using device: {SelectedInterface} (ID: {device_index})")
if args.continuous:
if args.pushtodb:
token = os.environ.get("INFLUXDB_TOKEN")
org = "lhep"
url = "http://argoncube02.aec.unibe.ch:8086"
write_client = influxdb_client.InfluxDBClient(url=url, token=token, org=org)
bucket="fsd_sc"
write_api = write_client.write_api(write_options=SYNCHRONOUS)
total_time_in_seconds = args.total_time * 3600
interval_in_seconds = args.interval
start_time = time.time()
elapsed_time = 0
folder_name = f"Continuousrecording_{current_date}_{current_time}"
os.makedirs(folder_name, exist_ok=True)
while elapsed_time < total_time_in_seconds:
start_record_time = time.time()
OUTPUT_FILENAME = f"{folder_name}/Recording_{args.duration}s_{current_date}_{current_time}.wav"
audio_data = record_sample(device_index, args.duration, OUTPUT_FILENAME)
if args.split:
sample_width = audio.get_sample_size(FORMAT)
split_audio(audio_data, sample_width, CHANNELS, 0.5, RATE, OUTPUT_FILENAME)
if os.path.exists(REFERENCE_FILENAME):
print(f"Comparing recording with reference file: {REFERENCE_FILENAME}")
integrated_value = plot_fft_comparison(OUTPUT_FILENAME, REFERENCE_FILENAME, continuous_mode=True)
if args.pushtodb:
point = (
Point("vibmon")
.tag("fq_range", "20_1000hz")
.field("value", integrated_value)
)
write_api.write(bucket=bucket, org="lhep", record=point)
elapsed_time = time.time() - start_time
if elapsed_time < total_time_in_seconds:
recording_duration = time.time() - start_record_time
wait_time = interval_in_seconds - recording_duration
if wait_time >0:
print(f"Waiting for {args.interval} seconds before next recording.")
time.sleep(wait_time)
else:
RECORD_SECONDS = args.duration
OUTPUT_FILENAME = f"Recording_{RECORD_SECONDS}s_{current_date}_{current_time}.wav"
audio_data = record_sample(device_index, RECORD_SECONDS, OUTPUT_FILENAME)
plot_stereo_waveform(OUTPUT_FILENAME)
compare_fft(OUTPUT_FILENAME, REFERENCE_FILENAME, RATE)
print("Recording finished")
if args.split:
OUTPUT_DIR = F"Splits_{current_date}_{current_time}"
os.makedirs(OUTPUT_DIR, exist_ok=True)
print(f"Splitting the {RECORD_SECONDS}s Recording into 0.5s parts")
sample_width = audio.get_sample_size(FORMAT)
num_channels = CHANNELS
split_audio(audio_data, sample_width, num_channels, 0.5, RATE, f"{OUTPUT_DIR}/Recording_{current_date}_{current_time}")
#if os.path.exists(REFERENCE_FILENAME):
#print(f"Comparing recording with reference file: {REFERENCE_FILENAME}")
#plot_fft_comparison(OUTPUT_FILENAME, REFERENCE_FILENAME, continuous_mode=args.continuous)
#else:
#print(f"Reference file {REFERENCE_FILENAME} not found. Skipping comparison.")
# Ensure that PyAudio is terminated after execution
def cleanup():
audio.terminate()
if __name__ == "__main__":
try:
main()
finally:
cleanup()