-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
64 lines (55 loc) · 2.47 KB
/
common.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
import librosa, librosa.display
import matplotlib.pyplot as plt
import numpy as np
class Utils:
@staticmethod
def read_audio_file(file_path):
data, sr = librosa.core.load(file_path, mono=True, sr=None)
return data, sr
@staticmethod
def write_audio_file(file_path, data, sr):
librosa.output.write_wav(file_path, data, sr)
@staticmethod
def get_plot_data(data, sr, graph_type):
if graph_type == "melspectrogram":
S = librosa.feature.melspectrogram(y=data, sr=sr)
return librosa.power_to_db(S, ref=np.max)
elif graph_type == "melspectrogram-energy":
S = librosa.feature.melspectrogram(y=data, sr=sr, power=1)
return librosa.amplitude_to_db(S, ref=np.max)
elif graph_type == "mfcc":
return librosa.feature.mfcc(y=data, sr=sr)
elif graph_type == "spectrogram":
stft = librosa.core.spectrum.stft(data, hop_length=512)
return librosa.amplitude_to_db(np.abs(stft), ref=np.max)
elif graph_type == "filterbank":
S = librosa.feature.melspectrogram(y=data, sr=sr, hop_length=512)
return librosa.core.amplitude_to_db(S, ref=np.max)
@staticmethod
def write_graph(data, sr, file_path, graph_type):
fig = plt.figure(figsize=(10, 4))
if graph_type == "melspectrogram":
librosa.display.specshow(data, sr=sr,
y_axis='mel', fmax=8000, x_axis='time', ax=None)
elif graph_type == "mfcc":
librosa.display.specshow(data, sr=sr,
x_axis='time', ax=None)
elif graph_type == "melspectrogram-energy":
librosa.display.specshow(data, sr=sr,
y_axis='mel', fmax=8000, x_axis='time', ax=None)
elif graph_type == "spectrogram":
librosa.display.specshow(data, sr=sr, ax=None, y_axis='log', x_axis='time')
elif graph_type == "filterbank":
librosa.display.specshow(data, sr=sr, ax=None, y_axis='log', hop_length=512, x_axis='frames')
plt.margins(0)
for ax in fig.get_axes():
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.label.set_visible(False)
ax.yaxis.label.set_visible(False)
ax.grid(False)
plt.xticks([])
plt.yticks([])
plt.tight_layout()
plt.savefig(file_path)
plt.close()