bioamla.audio¶
bioamla.audio ¶
bioamla.audio — the foundational audio domain.
Data container (:class:AudioData), file I/O, discovery, analysis, signal
processing, and playback. Heavy backends are imported lazily inside the
functions that need them (torchaudio for waveform tensors, sounddevice for
playback), so importing this package stays fast.
AmplitudeStats
dataclass
¶
Amplitude statistics for audio.
Attributes:
| Name | Type | Description |
|---|---|---|
rms |
float
|
Root mean square amplitude (0.0 to 1.0) |
rms_db |
float
|
RMS level in dB (relative to full scale) |
peak |
float
|
Peak absolute amplitude (0.0 to 1.0) |
peak_db |
float
|
Peak level in dBFS |
crest_factor |
float
|
Peak to RMS ratio (in dB) |
dynamic_range |
float
|
Difference between peak and RMS in dB |
FrequencyStats
dataclass
¶
Frequency statistics for audio.
Attributes:
| Name | Type | Description |
|---|---|---|
peak_frequency |
float
|
Frequency with highest magnitude in Hz |
peak_magnitude |
float
|
Magnitude at peak frequency |
mean_frequency |
float
|
Weighted mean frequency in Hz |
min_frequency |
float
|
Lowest significant frequency in Hz |
max_frequency |
float
|
Highest significant frequency in Hz |
bandwidth |
float
|
Frequency bandwidth (max - min) in Hz |
spectral_centroid |
float
|
Spectral centroid (center of mass) in Hz |
spectral_rolloff |
float
|
Frequency below which 85% of energy is contained |
SilenceInfo
dataclass
¶
Silence detection results.
Attributes:
| Name | Type | Description |
|---|---|---|
is_silent |
bool
|
True if audio is considered silent |
silence_ratio |
float
|
Ratio of silent samples to total samples (0.0-1.0) |
sound_ratio |
float
|
Ratio of non-silent samples to total samples (0.0-1.0) |
silent_segments |
list[tuple[float, float]]
|
List of (start_time, end_time) tuples for silent regions |
sound_segments |
list[tuple[float, float]]
|
List of (start_time, end_time) tuples for non-silent regions |
threshold_used |
float
|
The amplitude threshold used for detection |
AudioData
dataclass
¶
Bases: ToDictMixin
Container for audio data with metadata.
This is the primary in-memory data transfer object for audio. I/O functions
in :mod:bioamla.audio.io produce and consume AudioData; transforms
operate on it.
Attributes:
| Name | Type | Description |
|---|---|---|
samples |
ndarray
|
Audio samples as a numpy array. |
sample_rate |
int
|
Sample rate in Hz. |
channels |
int
|
Number of channels (1 = mono). |
source_path |
str | None
|
Path the audio was loaded from, if any. |
is_modified |
bool
|
Whether the samples have been modified since loading. |
metadata |
dict[str, Any]
|
Arbitrary metadata dictionary. |
AudioMetadata
dataclass
¶
Bases: ToDictMixin
Metadata about an audio file.
Attributes:
| Name | Type | Description |
|---|---|---|
filepath |
str
|
Path to the file. |
duration_seconds |
float
|
Duration in seconds. |
sample_rate |
int
|
Sample rate in Hz. |
channels |
int
|
Number of channels. |
bit_depth |
int | None
|
Bit depth, if known. |
format |
str | None
|
Container/codec format, if known. |
ProcessedAudio
dataclass
¶
Bases: ToDictMixin
Result of processing an audio file.
Attributes:
| Name | Type | Description |
|---|---|---|
input_path |
str
|
Source file path. |
output_path |
str
|
Destination file path. |
operation |
str
|
Human-readable description of the operation performed. |
sample_rate |
int
|
Sample rate of the output in Hz. |
duration_seconds |
float
|
Duration of the output in seconds. |
AudioAnalysis
dataclass
¶
Complete audio analysis results.
Attributes:
| Name | Type | Description |
|---|---|---|
file_path |
str
|
Path to the analyzed audio file. |
info |
AudioInfo
|
Basic audio information. |
amplitude |
AmplitudeStats
|
Amplitude statistics. |
frequency |
FrequencyStats
|
Frequency statistics. |
silence |
SilenceInfo
|
Silence detection results. |
AudioInfo
dataclass
¶
Basic audio file information.
Attributes:
| Name | Type | Description |
|---|---|---|
duration |
float
|
Duration in seconds. |
sample_rate |
int
|
Sample rate in Hz. |
channels |
int
|
Number of audio channels. |
samples |
int
|
Total number of samples. |
bit_depth |
int | None
|
Bit depth (if available). |
format |
str | None
|
Audio format (e.g., 'WAV', 'FLAC'). |
subtype |
str | None
|
Audio subtype (e.g., 'PCM_16'). |
AudioPlayer ¶
Audio player with play, pause, stop, and seek functionality.
Provides a simple interface for playing audio through the system's audio
output using sounddevice. Supports play/pause/stop controls, seeking
(by time or sample), looping, and playback-event callbacks.
Note
Uses sounddevice (a base dependency) for audio output.
load ¶
load(
audio: ndarray,
sample_rate: int,
on_complete: Callable[[], None] | None = None,
on_position_change: Callable[[PlaybackPosition], None]
| None = None,
) -> None
Load audio data for playback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array (mono or stereo). |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
on_complete
|
Callable[[], None] | None
|
Optional callback when playback completes. |
None
|
on_position_change
|
Callable[[PlaybackPosition], None] | None
|
Optional callback for position updates. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the audio array has an unexpected shape. |
load_file ¶
load_file(
filepath: str,
on_complete: Callable[[], None] | None = None,
on_position_change: Callable[[PlaybackPosition], None]
| None = None,
) -> None
Load audio from a file for playback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the audio file. |
required |
on_complete
|
Callable[[], None] | None
|
Optional callback when playback completes. |
None
|
on_position_change
|
Callable[[PlaybackPosition], None] | None
|
Optional callback for position updates. |
None
|
play ¶
play(loop: bool = False) -> None
Start or resume playback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loop
|
bool
|
If True, loop the audio continuously. |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no audio has been loaded. |
seek ¶
seek(
time_or_sample: float | int, by_sample: bool = False
) -> None
Seek to a specific position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_or_sample
|
float | int
|
Position to seek to (seconds or sample index). |
required |
by_sample
|
bool
|
If True, interpret position as sample index. If False (default), interpret as time in seconds. |
False
|
PlaybackPosition
dataclass
¶
Current playback position information.
PlaybackState ¶
Bases: Enum
Enumeration of playback states.
AudioEvent
dataclass
¶
Represents a detected audio event.
AudioSegment
dataclass
¶
Represents a segment of audio.
calculate_dbfs ¶
calculate_dbfs(
amplitude: float, reference: float = 1.0
) -> float
Convert linear amplitude to decibels relative to full scale (dBFS).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amplitude
|
float
|
Linear amplitude value. |
required |
reference
|
float
|
Reference amplitude for full scale (default: 1.0). |
1.0
|
Returns:
| Type | Description |
|---|---|
float
|
Amplitude in dBFS (always negative or zero for normalized audio). |
calculate_peak ¶
calculate_peak(audio: ndarray) -> float
Calculate the peak absolute amplitude of audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Peak absolute amplitude (0.0 to 1.0+ for normalized audio). |
calculate_rms ¶
calculate_rms(audio: ndarray) -> float
Calculate the Root Mean Square (RMS) amplitude of audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
Returns:
| Type | Description |
|---|---|
float
|
RMS amplitude (0.0 to 1.0 for normalized audio). |
detect_silence ¶
detect_silence(
audio: ndarray,
sample_rate: int,
threshold_db: float = -40,
min_silence_duration: float = 0.1,
min_sound_duration: float = 0.1,
) -> SilenceInfo
Detect silent and non-silent regions in audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
threshold_db
|
float
|
Threshold in dBFS below which is considered silence. |
-40
|
min_silence_duration
|
float
|
Minimum duration in seconds for a silent region. |
0.1
|
min_sound_duration
|
float
|
Minimum duration in seconds for a sound region. |
0.1
|
Returns:
| Type | Description |
|---|---|
SilenceInfo
|
class: |
get_amplitude_stats ¶
get_amplitude_stats(audio: ndarray) -> AmplitudeStats
Calculate comprehensive amplitude statistics for audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
Returns:
| Type | Description |
|---|---|
AmplitudeStats
|
class: |
get_frequency_stats ¶
get_frequency_stats(
audio: ndarray,
sample_rate: int,
n_fft: int = 2048,
threshold_db: float = -60,
) -> FrequencyStats
Calculate comprehensive frequency statistics for audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
n_fft
|
int
|
FFT window size. |
2048
|
threshold_db
|
float
|
Threshold in dB below peak for significant frequencies. |
-60
|
Returns:
| Type | Description |
|---|---|
FrequencyStats
|
class: |
get_peak_frequency ¶
get_peak_frequency(
audio: ndarray,
sample_rate: int,
n_fft: int = 2048,
min_freq: float | None = None,
max_freq: float | None = None,
) -> tuple[float, float]
Find the frequency with the highest magnitude.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
n_fft
|
int
|
FFT window size. |
2048
|
min_freq
|
float | None
|
Minimum frequency to consider (optional). |
None
|
max_freq
|
float | None
|
Maximum frequency to consider (optional). |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple of (peak_frequency_hz, magnitude). |
is_silent ¶
is_silent(
audio: ndarray, threshold_db: float = -40
) -> bool
Quick check if audio is mostly silent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
threshold_db
|
float
|
Threshold in dBFS below which is considered silence. |
-40
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the audio is considered silent. |
batch_convert_files ¶
batch_convert_files(
input_dir: str,
output_dir: str,
*,
target_format: str = "wav",
sample_rate: int | None = None,
channels: int | None = None,
delete_original: bool = False,
recursive: bool = True,
max_workers: int = 1,
continue_on_error: bool = True,
on_progress: Callable[[int, int], None] | None = None,
) -> BatchResult
Convert every audio file in a directory to target_format.
Preserves the relative directory structure under output_dir and changes
each file's extension to match the target format. Optionally re-channels,
resamples, and deletes the originals.
See :func:bioamla.audio.convert.convert_audio_file for the per-file
semantics.
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the input directory does not exist. |
batch_resample_files ¶
batch_resample_files(
input_dir: str,
output_dir: str,
target_sample_rate: int,
*,
recursive: bool = True,
max_workers: int = 1,
continue_on_error: bool = True,
on_progress: Callable[[int, int], None] | None = None,
) -> BatchResult
Resample every audio file in a directory to target_sample_rate.
See :func:batch_transform_files for shared argument semantics.
batch_transform_files ¶
batch_transform_files(
input_dir: str,
output_dir: str,
processor_fn: Callable[[ndarray, int], ndarray],
*,
sample_rate: int | None = None,
recursive: bool = True,
max_workers: int = 1,
continue_on_error: bool = True,
on_progress: Callable[[int, int], None] | None = None,
) -> BatchResult
Apply a per-file transform to every audio file in a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
str
|
Directory containing the input audio files. |
required |
output_dir
|
str
|
Directory to write the processed |
required |
processor_fn
|
Callable[[ndarray, int], ndarray]
|
Callable taking |
required |
sample_rate
|
int | None
|
Optional target sample rate for the outputs. |
None
|
recursive
|
bool
|
Search subdirectories. |
True
|
max_workers
|
int
|
Number of worker processes (1 = sequential). |
1
|
continue_on_error
|
bool
|
Collect per-file errors and keep going if True. |
True
|
on_progress
|
Callable[[int, int], None] | None
|
Optional |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
BatchResult
|
class: |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the input directory does not exist. |
segment_audio_file ¶
segment_audio_file(
input_path: str,
output_dir: str,
*,
duration: float,
overlap: float = 0.0,
prefix: str | None = None,
) -> list[SegmentInfo]
Split one audio file into fixed-duration segments written under output_dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Source audio file. |
required |
output_dir
|
str
|
Directory the segment |
required |
duration
|
float
|
Segment duration in seconds. |
required |
overlap
|
float
|
Overlap between consecutive segments in seconds. |
0.0
|
prefix
|
str | None
|
Filename prefix for segments (defaults to the input stem). |
None
|
Returns:
| Type | Description |
|---|---|
list[SegmentInfo]
|
A list of :class: |
Raises:
| Type | Description |
|---|---|
InvalidInputError
|
If |
convert_audio_file ¶
convert_audio_file(
input_path: str | Path,
output_path: str | Path,
*,
target_format: str = "wav",
target_sample_rate: int | None = None,
target_channels: int | None = None,
delete_original: bool = False,
) -> str
Convert an audio file to a target format, optionally re-channel/resample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str | Path
|
Source audio file. |
required |
output_path
|
str | Path
|
Destination file path (its suffix should match
|
required |
target_format
|
str
|
Output container/codec ("wav", "mp3", "flac", "ogg"). |
'wav'
|
target_sample_rate
|
int | None
|
Resample to this rate before saving (optional). |
None
|
target_channels
|
int | None
|
Output channel count (1 = mono, 2 = stereo); optional. |
None
|
delete_original
|
bool
|
Delete the source file after a successful conversion (only when the output path differs from the input path). |
False
|
Returns:
| Type | Description |
|---|---|
str
|
The output path as a string. |
Raises:
| Type | Description |
|---|---|
InvalidInputError
|
If |
AudioLoadError / AudioSaveError
|
On I/O failure. |
get_audio_files ¶
get_audio_files(
directory: str | Path,
extensions: list[str] | None = None,
recursive: bool = True,
) -> list[str]
Get a list of audio files in a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Path to the directory to search |
required |
extensions
|
list[str] | None
|
List of audio file extensions to include. Defaults to SUPPORTED_AUDIO_EXTENSIONS if None. |
None
|
recursive
|
bool
|
If True, search subdirectories recursively |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of audio file paths (strings) matching the criteria. |
get_wav_metadata ¶
get_wav_metadata(filepath: str) -> dict[str, Any]
Get metadata from an audio file (WAV, MP3, FLAC, OGG, M4A, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the audio file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with audio metadata (sample_rate, channels, frames, duration, |
dict[str, Any]
|
format, subtype, bit_depth). |
list_audio_files ¶
list_audio_files(
directory: str | Path, recursive: bool = True
) -> list[Path]
List audio files in a directory as :class:~pathlib.Path objects.
Filters by :data:SUPPORTED_AUDIO_EXTENSIONS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Directory to search. |
required |
recursive
|
bool
|
If True, search subdirectories recursively. |
True
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
Sorted list of audio file paths. |
analyze_audio ¶
analyze_audio(
filepath: str, silence_threshold_db: float = -40
) -> AudioAnalysis
Perform complete audio analysis on a file.
Combines metadata, amplitude, frequency, and silence analysis into a single comprehensive result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the audio file. |
required |
silence_threshold_db
|
float
|
Threshold for silence detection in dBFS. |
-40
|
Returns:
| Type | Description |
|---|---|
AudioAnalysis
|
class: |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the file does not exist. |
AudioLoadError
|
If the audio cannot be loaded. |
analyze_audio_batch ¶
analyze_audio_batch(
filepaths: list[str],
silence_threshold_db: float = -40,
verbose: bool = True,
) -> list[AudioAnalysis]
Analyze multiple audio files.
Failures are logged and skipped (graceful batch behaviour) rather than aborting the whole run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepaths
|
list[str]
|
List of paths to audio files. |
required |
silence_threshold_db
|
float
|
Threshold for silence detection in dBFS. |
-40
|
verbose
|
bool
|
Print progress. |
True
|
Returns:
| Type | Description |
|---|---|
list[AudioAnalysis]
|
List of :class: |
get_audio_info ¶
get_audio_info(filepath: str) -> AudioInfo
Get basic information about an audio file.
Extracts metadata without loading the entire audio into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the audio file. |
required |
Returns:
| Type | Description |
|---|---|
AudioInfo
|
class: |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the file does not exist. |
AudioLoadError
|
If metadata cannot be extracted. |
summarize_analysis ¶
summarize_analysis(
analyses: list[AudioAnalysis],
) -> dict[str, Any]
Summarize analysis results from multiple files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
analyses
|
list[AudioAnalysis]
|
List of :class: |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with summary statistics. |
batch_process ¶
batch_process(
input_dir: str,
output_dir: str,
processor_fn: Callable[[ndarray, int], ndarray],
sample_rate: int | None = None,
recursive: bool = True,
verbose: bool = True,
) -> dict
Process all audio files in a directory.
Per-file failures are caught and logged (graceful batch behaviour).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
str
|
Path to the input directory. |
required |
output_dir
|
str
|
Path to the output directory. |
required |
processor_fn
|
Callable[[ndarray, int], ndarray]
|
Callable taking |
required |
sample_rate
|
int | None
|
Optional target sample rate for the output. |
None
|
recursive
|
bool
|
Search subdirectories. |
True
|
verbose
|
bool
|
Print progress. |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
Statistics dict with |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the input directory does not exist. |
create_temp_audio_file ¶
create_temp_audio_file(
audio: AudioData, suffix: str = ".wav"
) -> Path
Write :class:AudioData to a temporary file and return its path.
The temporary file is created with delete=False; the caller owns
cleanup of the returned path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
AudioData
|
Audio data to write. |
required |
suffix
|
str
|
File extension for the temporary file. |
'.wav'
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the created temporary file. |
Raises:
| Type | Description |
|---|---|
AudioSaveError
|
If encoding/writing fails. |
load_audio ¶
load_audio(filepath: str) -> tuple[np.ndarray, int]
Load an audio file as a mono numpy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the audio file. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, int]
|
Tuple of (audio array, sample rate). The array is mono float32. |
Raises:
| Type | Description |
|---|---|
AudioLoadError
|
If decoding fails. |
load_audio_data ¶
load_audio_data(
filepath: str | Path, *, sample_rate: int | None = None
) -> AudioData
Load an audio file into an :class:AudioData.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the audio file. |
required |
sample_rate
|
int | None
|
If given, resample the loaded audio to this rate. |
None
|
Returns:
| Type | Description |
|---|---|
AudioData
|
The loaded :class: |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the file does not exist. |
AudioLoadError
|
If decoding fails. |
load_waveform_tensor ¶
load_waveform_tensor(filepath: str) -> tuple
Load an audio file as a torch waveform tensor.
Thin re-export of the canonical torch-IO implementation in
:mod:bioamla.audio.torchaudio, kept here for the public bioamla.audio
surface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the audio file. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (waveform tensor, sample rate). |
Raises:
| Type | Description |
|---|---|
AudioLoadError
|
If decoding fails. |
process_file ¶
process_file(
input_path: str,
output_path: str,
processor_fn: Callable[[ndarray, int], ndarray],
sample_rate: int | None = None,
) -> str
Load, process, and save a single audio file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Path to the input file. |
required |
output_path
|
str
|
Path to the output file. |
required |
processor_fn
|
Callable[[ndarray, int], ndarray]
|
Callable taking |
required |
sample_rate
|
int | None
|
Optional target sample rate for the output. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the output file. |
Raises:
| Type | Description |
|---|---|
AudioLoadError
|
If the input cannot be loaded. |
AudioSaveError
|
If the output cannot be saved. |
save_audio ¶
save_audio(
filepath: str,
audio: ndarray,
sample_rate: int,
format: str | None = None,
) -> str
Save a numpy audio array to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Destination file path. |
required |
audio
|
ndarray
|
Audio data as a numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
format
|
str | None
|
Output format (auto-detected from the extension if not given). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the saved file (as a string). |
Raises:
| Type | Description |
|---|---|
AudioSaveError
|
If encoding/writing fails. |
save_audio_data ¶
save_audio_data(
audio: AudioData,
output_path: str | Path,
*,
format: str | None = None,
) -> Path
Save :class:AudioData to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
AudioData
|
Audio data to save. |
required |
output_path
|
str | Path
|
Destination file path. |
required |
format
|
str | None
|
Audio format (auto-detected from extension if not specified). |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The output :class: |
Raises:
| Type | Description |
|---|---|
AudioSaveError
|
If encoding/writing fails. |
save_audio_data_as ¶
save_audio_data_as(
audio: AudioData,
output_path: str | Path,
*,
target_sample_rate: int | None = None,
format: str | None = None,
) -> Path
Save :class:AudioData to a new file, optionally resampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
AudioData
|
Audio data to save. |
required |
output_path
|
str | Path
|
Destination file path. |
required |
target_sample_rate
|
int | None
|
Resample to this rate before saving (optional). |
None
|
format
|
str | None
|
Audio format (auto-detected from extension if not specified). |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The output :class: |
Raises:
| Type | Description |
|---|---|
AudioSaveError
|
If resampling or encoding/writing fails. |
play_audio ¶
play_audio(
audio_or_filepath: ndarray | str,
sample_rate: int | None = None,
loop: bool = False,
block: bool = False,
) -> AudioPlayer
Play audio data or a file.
Convenience function that creates or reuses a global :class:AudioPlayer.
For more control, create your own :class:AudioPlayer instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio_or_filepath
|
ndarray | str
|
Either a numpy array of audio data or a path to an audio file. |
required |
sample_rate
|
int | None
|
Sample rate (required if |
None
|
loop
|
bool
|
If True, loop the audio continuously. |
False
|
block
|
bool
|
If True, block until playback completes. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
AudioPlayer
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a numpy array is given without a sample rate. |
add_noise ¶
add_noise(
audio: ndarray, snr_db: float, seed: int | None = None
) -> np.ndarray
Add Gaussian white noise at a target signal-to-noise ratio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
snr_db
|
float
|
Target SNR in dB; lower values add more noise. |
required |
seed
|
int | None
|
Optional RNG seed for reproducible noise. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Noisy audio as numpy array. |
apply_gain ¶
apply_gain(audio: ndarray, gain_db: float) -> np.ndarray
Apply a fixed gain (in dB) to audio, clipping to [-1, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
gain_db
|
float
|
Gain to apply in dB; positive amplifies, negative attenuates. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Gain-adjusted audio as numpy array. |
bandpass_filter ¶
bandpass_filter(
audio: ndarray,
sample_rate: int,
low_freq: float,
high_freq: float,
order: int = 5,
) -> np.ndarray
Apply a bandpass filter to audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
low_freq
|
float
|
Low cutoff frequency in Hz. |
required |
high_freq
|
float
|
High cutoff frequency in Hz. |
required |
order
|
int
|
Filter order (default: 5). |
5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Filtered audio as numpy array. |
Raises:
| Type | Description |
|---|---|
ProcessingError
|
If the low cutoff is not below the high cutoff. |
detect_onsets ¶
detect_onsets(
audio: ndarray,
sample_rate: int,
method: str = "energy",
threshold: float = 0.1,
) -> list[AudioEvent]
Detect onset events in audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
method
|
str
|
Detection method ('energy', 'spectral', 'complex'). |
'energy'
|
threshold
|
float
|
Detection threshold (0-1). |
0.1
|
Returns:
| Type | Description |
|---|---|
list[AudioEvent]
|
List of :class: |
highpass_filter ¶
highpass_filter(
audio: ndarray,
sample_rate: int,
cutoff_freq: float,
order: int = 5,
) -> np.ndarray
Apply a highpass filter to audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
cutoff_freq
|
float
|
Cutoff frequency in Hz. |
required |
order
|
int
|
Filter order (default: 5). |
5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Filtered audio as numpy array. |
lowpass_filter ¶
lowpass_filter(
audio: ndarray,
sample_rate: int,
cutoff_freq: float,
order: int = 5,
) -> np.ndarray
Apply a lowpass filter to audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
cutoff_freq
|
float
|
Cutoff frequency in Hz. |
required |
order
|
int
|
Filter order (default: 5). |
5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Filtered audio as numpy array. |
normalize_loudness ¶
normalize_loudness(
audio: ndarray, sample_rate: int, target_db: float = -20
) -> np.ndarray
Normalize audio to target loudness level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
target_db
|
float
|
Target loudness in dB (default: -20). |
-20
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized audio as numpy array. |
peak_normalize ¶
peak_normalize(
audio: ndarray, target_peak: float = 0.95
) -> np.ndarray
Normalize audio to target peak level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
target_peak
|
float
|
Target peak level (0-1, default: 0.95). |
0.95
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized audio as numpy array. |
pitch_shift ¶
pitch_shift(
audio: ndarray, sample_rate: int, n_steps: float
) -> np.ndarray
Shift the pitch of audio up or down without changing its duration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
n_steps
|
float
|
Number of (fractional) semitones to shift; positive raises pitch. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Pitch-shifted audio as numpy array. |
resample_audio ¶
resample_audio(
audio: ndarray, orig_sr: int, target_sr: int
) -> np.ndarray
Resample audio to a different sample rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
orig_sr
|
int
|
Original sample rate in Hz. |
required |
target_sr
|
int
|
Target sample rate in Hz. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Resampled audio as numpy array. |
segment_on_silence ¶
segment_on_silence(
audio: ndarray,
sample_rate: int,
silence_threshold_db: float = -40,
min_silence_duration: float = 0.3,
min_segment_duration: float = 0.5,
) -> list[AudioSegment]
Split audio on silence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
silence_threshold_db
|
float
|
Threshold in dB below which is considered silence. |
-40
|
min_silence_duration
|
float
|
Minimum silence duration in seconds to split on. |
0.3
|
min_segment_duration
|
float
|
Minimum segment duration in seconds to keep. |
0.5
|
Returns:
| Type | Description |
|---|---|
list[AudioSegment]
|
List of :class: |
spectral_denoise ¶
spectral_denoise(
audio: ndarray,
sample_rate: int,
noise_reduce_factor: float = 1.0,
n_fft: int = 2048,
hop_length: int = 512,
) -> np.ndarray
Apply spectral noise reduction using spectral gating.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
noise_reduce_factor
|
float
|
How aggressively to reduce noise (0-2, default: 1.0). |
1.0
|
n_fft
|
int
|
FFT window size. |
2048
|
hop_length
|
int
|
Hop length for STFT. |
512
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Denoised audio as numpy array. |
split_audio_on_silence ¶
split_audio_on_silence(
audio: ndarray,
sample_rate: int,
silence_threshold_db: float = -40,
min_silence_duration: float = 0.3,
min_segment_duration: float = 0.5,
) -> list[tuple[np.ndarray, float, float]]
Split audio on silence and return audio chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
silence_threshold_db
|
float
|
Threshold in dB below which is considered silence. |
-40
|
min_silence_duration
|
float
|
Minimum silence duration in seconds to split on. |
0.3
|
min_segment_duration
|
float
|
Minimum segment duration in seconds to keep. |
0.5
|
Returns:
| Type | Description |
|---|---|
list[tuple[ndarray, float, float]]
|
List of tuples (audio_chunk, start_time, end_time). |
time_stretch ¶
time_stretch(audio: ndarray, rate: float) -> np.ndarray
Time-stretch audio without changing its pitch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
rate
|
float
|
Stretch factor; |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Time-stretched audio as numpy array. |
Raises:
| Type | Description |
|---|---|
ProcessingError
|
If |
trim_audio ¶
trim_audio(
audio: ndarray,
sample_rate: int,
start_time: float | None = None,
end_time: float | None = None,
) -> np.ndarray
Trim audio to specified time range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
start_time
|
float | None
|
Start time in seconds (None = beginning). |
None
|
end_time
|
float | None
|
End time in seconds (None = end). |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Trimmed audio as numpy array. |
Raises:
| Type | Description |
|---|---|
ProcessingError
|
If the resulting trim range is empty. |
trim_silence ¶
trim_silence(
audio: ndarray,
sample_rate: int,
threshold_db: float = -40,
margin: float = 0.1,
) -> np.ndarray
Trim silence from beginning and end of audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Audio data as numpy array. |
required |
sample_rate
|
int
|
Sample rate in Hz. |
required |
threshold_db
|
float
|
Threshold in dB below which is considered silence. |
-40
|
margin
|
float
|
Additional margin to keep in seconds. |
0.1
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Trimmed audio as numpy array. |
resample_waveform_tensor ¶
resample_waveform_tensor(
waveform_tensor: Tensor, orig_freq: int, new_freq: int
) -> torch.Tensor
Resample a waveform tensor to a different sample rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
waveform_tensor
|
Tensor
|
Input waveform tensor. |
required |
orig_freq
|
int
|
Original sample rate in Hz. |
required |
new_freq
|
int
|
Target sample rate in Hz. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Resampled waveform tensor. |
split_waveform_tensor ¶
split_waveform_tensor(
waveform_tensor: Tensor,
freq: int,
segment_duration: int,
segment_overlap: int,
) -> list[tuple[torch.Tensor, int, int]]
Split a waveform tensor into overlapping fixed-length segments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
waveform_tensor
|
Tensor
|
Input waveform tensor. |
required |
freq
|
int
|
Sample rate of the audio. |
required |
segment_duration
|
int
|
Duration of each segment in seconds. |
required |
segment_overlap
|
int
|
Overlap between consecutive segments in seconds. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[Tensor, int, int]]
|
List of (segment_tensor, start_sample, end_sample) tuples. |