SpectrogramGenerator¶
Generate spectrograms from audio files with configurable parameters. Based on MATLAB spectrogram computation with normalization and dB conversion.
Initialize spectrogram generator with parameters from MATLAB code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
win_dur
|
float
|
Window duration in seconds (controls FFT size: NFFT = win_dur * fs) |
1.0
|
overlap
|
float
|
Overlap ratio between adjacent windows (0-1), higher = smoother time axis |
0.5
|
window_type
|
Union[str, Tuple[str, float], ndarray]
|
Window function name/tuple for scipy.signal.get_window (e.g., 'hann', ('kaiser', 14)) Custom arrays or unsupported window types fall back to the SciPy backend. |
'hann'
|
nfft
|
Optional[int]
|
FFT size in samples (None = derived from win_dur/sample_rate) |
None
|
win_length
|
Optional[int]
|
Window length in samples (None = use nfft) |
None
|
hop_length
|
Optional[int]
|
Step size in samples (None = derived from overlap ratio) |
None
|
freq_lims
|
Tuple[float, float]
|
Frequency limits for plotting [Hz] (and cropping if crop_freq_lims=True) |
(10, 10000)
|
colormap
|
str
|
Matplotlib colormap name |
'turbo'
|
clim
|
Tuple[float, float]
|
Color axis limits [dB] |
(-60, 0)
|
log_freq
|
bool
|
Whether to use logarithmic frequency scale |
True
|
crop_freq_lims
|
bool
|
If True, crop saved outputs to freq_lims |
False
|
max_duration
|
Optional[float]
|
Maximum duration to process in seconds (None = full file) |
None
|
clip_start
|
Optional[float]
|
Optional start time (seconds) to trim from beginning of audio |
None
|
clip_end
|
Optional[float]
|
Optional end time (seconds) to stop processing; must be > clip_start |
None
|
clip_pad_seconds
|
Union[float, str, None]
|
Extra context (seconds) to include on each side of the clip before the STFT; the spectrogram is trimmed back to the target window. Use 'auto' to pad by half the window length (helps reduce edge artifacts). |
'auto'
|
backend
|
str
|
'auto' (default), 'torch', or 'scipy' backend for spectrogram computation |
'auto'
|
torch_device
|
str
|
Torch device for spectrogram computation ('cpu', 'cuda', or 'auto') |
'cpu'
|
scaling
|
str
|
'density' (default) or 'spectrum' scaling for PSD normalization |
'density'
|
quiet
|
bool
|
If True, suppress logger noise (only minimal prints for progress bar) |
False
|
use_logging
|
bool
|
If False, fall back to stdout printing (avoids notebook logging friction) |
True
|
_cache_lock = threading.Lock()
instance-attribute
¶
_torch_transform_cache = {}
instance-attribute
¶
backend = backend
instance-attribute
¶
clim = clim
instance-attribute
¶
clip_end = clip_end
instance-attribute
¶
clip_pad_seconds = clip_pad_seconds
instance-attribute
¶
clip_start = clip_start
instance-attribute
¶
colormap = colormap
instance-attribute
¶
crop_freq_lims = crop_freq_lims
instance-attribute
¶
freq_lims = freq_lims
instance-attribute
¶
hop_length = hop_length
instance-attribute
¶
log = logger if use_logging else PrintLogger()
instance-attribute
¶
log_freq = log_freq
instance-attribute
¶
max_duration = max_duration
instance-attribute
¶
nfft = nfft
instance-attribute
¶
overlap = overlap
instance-attribute
¶
quiet = quiet
instance-attribute
¶
scaling = scaling
instance-attribute
¶
torch_device = torch_device
instance-attribute
¶
win_dur = win_dur
instance-attribute
¶
win_length = win_length
instance-attribute
¶
window_type = window_type
instance-attribute
¶
_apply_freq_lims(frequencies, power_spectrogram, power_db_norm)
¶
_describe_window_type()
¶
_get_torch_spectrogram_transform(*, nfft, win_length, hop_length, device, torch_window)
¶
Return a cached, stateless torchaudio transform.
_resolve_clip_pad_seconds(sample_rate)
¶
Resolve clip_pad_seconds, supporting an 'auto' mode.
_resolve_fft_params(sample_rate)
¶
_resolve_window(win_length)
¶
_sanitize_metadata_for_mat(value)
staticmethod
¶
_torch_window_spec()
¶
compute_spectrogram(audio_data, sample_rate, clip_meta=None)
¶
Compute spectrogram following MATLAB implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio_data
|
ndarray
|
Audio signal |
required |
sample_rate
|
int
|
Sample rate in Hz |
required |
clip_meta
|
Optional[dict]
|
Optional clip metadata to trim spectrogram to target window |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray, ndarray, ndarray]
|
Tuple of (frequencies, times, power_spectrogram, normalized_db) |
load_audio(audio_path)
¶
Load audio file supporting multiple formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio_path
|
Union[str, Path]
|
Path to audio file |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, int, Optional[dict]]
|
Tuple of (audio_data, sample_rate, clip_meta) |
plot_spectrogram(frequencies, times, power_db_norm, title='Spectrogram', save_path=None)
¶
Plot spectrogram following MATLAB visualization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies
|
ndarray
|
Frequency array |
required |
times
|
ndarray
|
Time array |
required |
power_db_norm
|
ndarray
|
Normalized power in dB |
required |
title
|
str
|
Plot title |
'Spectrogram'
|
save_path
|
Optional[Union[str, Path]]
|
Optional path to save plot |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
matplotlib Figure object |
process_directory(input_dir, save_dir, file_extensions=None, save_plot=True, save_mat=True, save_npy=False, max_workers=None, retain_arrays=False)
¶
Process all audio files in a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
Union[str, Path]
|
Directory containing audio files. |
required |
save_dir
|
Union[str, Path]
|
Directory to save outputs. |
required |
file_extensions
|
Optional[List[str]]
|
Audio file extensions to include. |
None
|
save_plot
|
bool
|
Save PNG plots (default: True). |
True
|
save_mat
|
bool
|
Save MATLAB |
True
|
save_npy
|
bool
|
Save NumPy |
False
|
max_workers
|
Optional[int]
|
Batch worker count. Defaults to at most four to limit peak memory; raise it explicitly for many short files. |
None
|
retain_arrays
|
bool
|
Keep full arrays in each result. Defaults to False so long batch jobs do not retain every spectrogram in memory. |
False
|
Returns:
| Type | Description |
|---|---|
List[dict]
|
List of processing result dicts (one per file). |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the input directory does not exist. |
process_event(audio_path, save_dir, event_time_seconds, *, pad_before_seconds=5.0, pad_after_seconds=None, edge_padding_seconds='auto', save_plot=True, save_mat=True, save_npy=False, extra_metadata=None, retain_arrays=True, output_stem=None)
¶
Generate an edge-safe spectrogram around an event in an audio file.
The retained target interval extends before and after
event_time_seconds. Additional audio context is included only while
computing the STFT, then frames are trimmed back to the target interval.
The default 'auto' context is half the resolved STFT window on each
side, so every retained frame has a complete analysis window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio_path
|
Union[str, Path]
|
Source audio file. |
required |
save_dir
|
Union[str, Path]
|
Directory for generated outputs. |
required |
event_time_seconds
|
float
|
Event offset from the start of the audio file. |
required |
pad_before_seconds
|
float
|
Target data retained before the event. Defaults to five seconds. |
5.0
|
pad_after_seconds
|
Optional[float]
|
Target data retained after the event. Defaults to
|
None
|
edge_padding_seconds
|
Union[float, str, None]
|
Extra computation-only context on each side.
Use |
'auto'
|
save_plot
|
bool
|
Save a PNG plot. |
True
|
save_mat
|
bool
|
Save MATLAB output. |
True
|
save_npy
|
bool
|
Save NumPy output. |
False
|
extra_metadata
|
Optional[dict]
|
Optional additional output metadata. |
None
|
retain_arrays
|
bool
|
Keep arrays in the returned result. |
True
|
output_stem
|
Optional[str]
|
Optional saved-output filename stem. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
The usual single-file result plus event and target-window metadata. |
process_single_file(audio_path, save_dir, save_plot=True, save_mat=True, save_npy=False, extra_metadata=None, retain_arrays=True, output_stem=None)
¶
Process a single audio file and generate a spectrogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio_path
|
Union[str, Path]
|
Path to the input audio file. |
required |
save_dir
|
Union[str, Path]
|
Output directory for generated files. |
required |
save_plot
|
bool
|
Save a PNG plot (default: True). |
True
|
save_mat
|
bool
|
Save MATLAB |
True
|
save_npy
|
bool
|
Save NumPy |
False
|
extra_metadata
|
Optional[dict]
|
Optional extra metadata to store in outputs. |
None
|
retain_arrays
|
bool
|
Keep full spectrogram arrays in the returned dict. Disable this for batch jobs to release memory after each file. |
True
|
output_stem
|
Optional[str]
|
Optional filename stem for saved outputs. Defaults to the input audio filename stem. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dict with file paths, arrays, and metadata. Keys include: |
dict
|
|
dict
|
|
dict
|
and any saved file paths ( |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the audio file does not exist. |
ValueError
|
If |
Example
generator = SpectrogramGenerator(win_dur=0.5, overlap=0.5)
result = generator.process_single_file(
"example.flac",
"./out",
save_mat=True,
save_plot=False,
)
print(result["mat_file"])
save_matlab_format(frequencies, times, power_spectrogram, power_db_norm, save_path, metadata=None)
¶
Save spectrogram data in MATLAB format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies
|
ndarray
|
Frequency array |
required |
times
|
ndarray
|
Time array |
required |
power_spectrogram
|
ndarray
|
Raw power spectrogram |
required |
power_db_norm
|
ndarray
|
Normalized power in dB |
required |
save_path
|
Union[str, Path]
|
Path to save .mat file |
required |
save_numpy_format(frequencies, times, power_spectrogram, power_db_norm, save_path, metadata=None)
¶
Save spectrogram data in numpy format.
Notes
This uses np.save with a dict payload (requires allow_pickle on load). Metadata is stored under the "metadata" key when provided.