-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdat2wav.py
More file actions
87 lines (72 loc) · 3.22 KB
/
dat2wav.py
File metadata and controls
87 lines (72 loc) · 3.22 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
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import write
# === Configuration ===
input_base = "/run/user/1000/gvfs/smb-share:server=filer01.hevs.ch,share=fs_projets/MatTechLab/monkey_call/00_rawdata_collars_2023"
output_base = "/run/user/1000/gvfs/smb-share:server=filer01.hevs.ch,share=fs_projets/MatTechLab/monkey_call/output"
sample_rate = 16000 # Hz
dtype = np.int16 # Signed 16-bit PCM
num_channels = 2 # 1 = mono, 2 = stereo
# === Prepare log file ===
log_path = os.path.join(output_base, "processing_log.csv")
os.makedirs(output_base, exist_ok=True)
log_entries = []
# === Recursively find .DAT files ===
for root, dirs, files in os.walk(input_base):
for filename in files:
if filename.lower().endswith(".dat"):
dat_path = os.path.join(root, filename)
# Skip empty files
if os.path.getsize(dat_path) == 0:
print(f"Skipping empty file: {dat_path}")
log_entries.append([dat_path, "", "", "Empty file"])
continue
print(f"Processing: {dat_path}")
# === Load the raw audio ===
with open(dat_path, "rb") as f:
audio_data = np.frombuffer(f.read(), dtype=dtype)
# === Reshape if stereo ===
if num_channels > 1:
try:
audio_data = audio_data.reshape(-1, num_channels)
except ValueError:
print(f"Warning: Cannot reshape file (size mismatch), skipping: {dat_path}")
log_entries.append([dat_path, "", "", "Reshape error"])
continue
# === Determine output folder ===
relative_path = os.path.relpath(root, input_base)
output_folder = os.path.join(output_base, relative_path)
os.makedirs(output_folder, exist_ok=True)
base_name = os.path.splitext(filename)[0]
wav_path = os.path.join(output_folder, base_name + ".wav")
png_path = os.path.join(output_folder, base_name + ".png")
# === Save WAV ===
write(wav_path, sample_rate, audio_data)
print(f"Saved WAV to: {wav_path}")
# === Save waveform plot ===
plt.figure(figsize=(10, 4))
if audio_data.ndim == 1:
plt.plot(audio_data[:1000])
plt.title(f"{base_name} (Mono)")
else:
plt.plot(audio_data[:1000, 0], label="Left")
plt.plot(audio_data[:1000, 1], label="Right")
plt.title(f"{base_name} (Stereo)")
plt.legend()
plt.xlabel("Sample")
plt.ylabel("Amplitude")
plt.tight_layout()
plt.savefig(png_path)
plt.close()
print(f"Saved waveform to: {png_path}")
# === Log success ===
log_entries.append([dat_path, wav_path, png_path, "OK"])
# === Write log file ===
with open(log_path, mode='w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["DAT file", "WAV output", "PNG output", "Status"])
writer.writerows(log_entries)
print(f"\n📋 Log written to: {log_path}")
print("🎉 Processing complete!")