Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
Quentin Aristote
Soundscapes
Commits
587ad623
Commit
587ad623
authored
Nov 30, 2019
by
Quentin Aristote
Browse files
added
parent
adfeade7
Changes
1
Hide whitespace changes
Inline
Side-by-side
data/get_spectrograms.py
0 → 100644
View file @
587ad623
# -*- coding: utf-8 -*-
import
librosa
import
os.path
import
pickle
import
warnings
def
soundToSpectrogram
(
path
,
samplerate
=
16000
)
:
"""Return the Mel Spectrogram of an audio file.
:param filename: the path to the file.
:param samplerate: the sample rate to use when getting the spectrogram."""
with
warnings
.
catch_warnings
()
:
warnings
.
filterwarnings
(
'ignore'
,
category
=
UserWarning
)
signal
,
samplerate
=
librosa
.
load
(
path
,
sr
=
samplerate
)
spectrogram
=
librosa
.
feature
.
melspectrogram
(
y
=
signal
,
sr
=
samplerate
)
return
spectrogram
def
getSpectrograms
(
source_directory
,
target_directory
,
samplerate
=
16000
,
overwrite
=
False
)
:
"""Compute the Mel spectrograms of all the sound files.
:param source_path: the directory where the sound files are.
:param target_path: the directory to save the the spectrograms to.
:param samplerate: the sample rate to use when getting the spectrogram."""
for
filename
in
os
.
listdir
(
source_directory
)
:
title
,
_
=
os
.
path
.
splitext
(
filename
)
source_path
=
os
.
path
.
join
(
source_directory
,
filename
)
target_path
=
os
.
path
.
join
(
target_directory
,
title
+
'.bin'
)
if
overwrite
:
mode
=
'w+b'
else
:
mode
=
'x+b'
print
(
'Computing the Mel spectrogram of {filename} ...'
.
format
(
filename
=
filename
))
try
:
with
open
(
target_path
,
mode
)
as
file
:
spectrogram
=
soundToSpectrogram
(
source_path
,
samplerate
=
samplerate
)
spectrogram
.
tofile
(
file
)
print
(
'Success.'
)
except
FileExistsError
as
exception
:
print
(
'Failure : {exception}'
.
format
(
exception
=
exception
))
if
__name__
==
'__main__'
:
getSpectrograms
(
'sounds'
,
'spectrograms'
)
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment