-
Notifications
You must be signed in to change notification settings - Fork 0
/
generation_dataset_method_2.py
69 lines (52 loc) · 2.19 KB
/
generation_dataset_method_2.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
import os
import librosa, librosa.display
import matplotlib.pyplot as plt
from matplotlib.backends.backend_template import FigureCanvas
import numpy as np
from pydub import AudioSegment
def generate_sample(filePath, directoryOfMultiSongs):
isExist = os.path.exists(directoryOfMultiSongs + '/' + filePath.split('\\')[-2])
if not isExist:
# Create a new directory because it does not exist
os.makedirs(directoryOfMultiSongs + '/' + filePath.split('\\')[-2])
print("The new directory is created!")
for w in range(0, 10):
# print(i)
t1 = 3 * (w) * 1000
t2 = 3 * (w + 1) * 1000
newAudio = AudioSegment.from_mp3(filePath)
new = newAudio[t1:t2]
new.export(directoryOfMultiSongs + '/' + '/'.join(
('.'.join(filePath.split('.')[:-1])).split('\\')[1:]) + f'{w + 1}' + '.wav',
format="wav")
def generate_images(filePath, directoryOfMelSpectrogram):
isExist = os.path.exists(directoryOfMelSpectrogram + '/' + filePath.split('\\')[-2])
if not isExist:
# Create a new directory because it does not exist
os.makedirs(directoryOfMelSpectrogram + '/' + filePath.split('\\')[-2])
print("The new directory is created!")
y, sr = librosa.load(filePath, duration=3)
# print(sr)
mels = librosa.feature.melspectrogram(y=y, sr=sr)
fig = plt.Figure()
canvas = FigureCanvas(fig)
p = plt.imshow(librosa.power_to_db(mels, ref=np.max))
plt.savefig(
directoryOfMelSpectrogram + '/' + '/'.join(('.'.join(filePath.split('.')[:-1])).split('\\')[1:]) + '.png')
if __name__ == '__main__':
# TODO: CONFIGURE
directoryOfSongs = "dataset"
directoryOfMultiSongs = "data"
directoryOfMelSpectrogram = "images"
for subdir, dirs, files in os.walk(directoryOfSongs):
for file in files:
try:
generate_sample(os.path.join(subdir, file), directoryOfMultiSongs)
except:
pass
for subdir, dirs, files in os.walk(directoryOfMultiSongs):
for file in files:
try:
generate_images(os.path.join(subdir, file), directoryOfMelSpectrogram)
except:
pass