-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwavToPng.py
More file actions
49 lines (40 loc) · 1.85 KB
/
wavToPng.py
File metadata and controls
49 lines (40 loc) · 1.85 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
import numpy as np
import librosa.display, os
import matplotlib.pyplot as plt
# This script creates spectrograms from WAV files and saves them as PNG images.
def create_spectrogram(audio_file, image_file):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
y, sr = librosa.load(audio_file)
ms = librosa.feature.melspectrogram(y=y, sr=sr)
log_ms = librosa.power_to_db(ms, ref=np.max)
librosa.display.specshow(log_ms, sr=sr)
fig.savefig(image_file)
plt.close(fig)
def create_pngs_from_wavs(input_path, output_path):
if not os.path.exists(output_path):
os.makedirs(output_path)
dir = os.listdir(input_path)
for file in dir:
if not file.lower().endswith('.wav'):
continue
output_file = os.path.join(output_path, file.replace('.wav', '.png'))
if os.path.exists(output_file):
continue # Skip if spectrogram already exists
input_file = os.path.join(input_path, file)
try:
create_spectrogram(input_file, output_file)
# Duplicate classes with less data
if file.startswith('4') or file.startswith('5'):
output_file2 = os.path.join(output_path, file.replace('.wav', '_2.png'))
create_spectrogram(input_file, output_file2)
output_file3 = os.path.join(output_path, file.replace('.wav', '_3.png'))
create_spectrogram(input_file, output_file3)
if file.startswith('5'):
output_file4 = os.path.join(output_path, file.replace('.wav', '_4.png'))
create_spectrogram(input_file, output_file4)
except Exception as e:
print(f"Error processing {input_file}: {e}")
create_pngs_from_wavs('wavData', 'Spectrograms')
print("Completed creating spectrograms from WAV files.")