Audio
Core audio class for loading, manipulating, analyzing, and saving audio files.
Audio
The Audio class handles audio data with numpy arrays, supporting operations like slicing, concatenation, overlay mixing, resampling, analysis, and format conversion.
from videopython.base import Audio
# Load from file
audio = Audio.from_file("music.mp3")
# Create silent track
silent = Audio.create_silent(duration_seconds=5.0, stereo=True)
# Basic operations
mono = audio.to_mono()
resampled = audio.resample(16000)
segment = audio.slice(start_seconds=1.0, end_seconds=5.0)
# Combine audio
combined = audio1.concat(audio2, crossfade=0.5)
mixed = audio1.overlay(audio2, position=2.0)
# Save
audio.save("output.wav")
Audio
A class to handle audio data with numpy arrays
Attributes:
| Name | Type | Description |
|---|---|---|
data |
ndarray
|
Audio data as a numpy array, normalized between -1 and 1 |
metadata |
AudioMetadata
|
Metadata about the audio file |
Source code in src/videopython/base/audio/audio.py
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 | |
is_silent
property
Check if the audio track is silent (all samples are effectively zero)
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the audio is silent, False otherwise |
__init__
Initialize Audio object
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
Audio data as numpy array, normalized between -1 and 1 |
required |
metadata
|
AudioMetadata
|
AudioMetadata object containing audio properties |
required |
Source code in src/videopython/base/audio/audio.py
create_silent
classmethod
create_silent(
duration_seconds: float,
stereo: bool = True,
sample_rate: int = 44100,
sample_width: int = 2,
) -> Audio
Create a silent audio track.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
duration_seconds
|
float
|
Length of the silent track in seconds |
required |
stereo
|
bool
|
If True, create stereo track; if False, create mono track (default: True) |
True
|
sample_rate
|
int
|
Sample rate in Hz (default: 44100) |
44100
|
sample_width
|
int
|
Sample width in bytes (default: 2, which is 16-bit) |
2
|
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio instance with silent track |
Raises:
| Type | Description |
|---|---|
ValueError
|
If duration is negative or other parameters are invalid |
Source code in src/videopython/base/audio/audio.py
from_file
classmethod
Load audio from a file using ffmpeg
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Path to the audio file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file doesn't exist |
AudioLoadError
|
If there's an error loading the audio |
Source code in src/videopython/base/audio/audio.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
to_mono
Convert stereo audio to mono by averaging channels
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio instance with mono audio |
Source code in src/videopython/base/audio/audio.py
get_channel
Extract a single channel from the audio
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
int
|
Channel number (0 for left, 1 for right) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio instance with single channel |
Raises:
| Type | Description |
|---|---|
ValueError
|
If channel number is invalid |
Source code in src/videopython/base/audio/audio.py
resample
Resample the audio to a new sample rate
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_sample_rate
|
int
|
New sample rate in Hz |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio instance with resampled audio |
Source code in src/videopython/base/audio/audio.py
concat
Concatenate another audio segment to this one. If mixing mono and stereo, converts mono to stereo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Audio
|
Another Audio object to concatenate |
required |
crossfade
|
float
|
Duration of crossfade in seconds (default: 0.0 for no crossfade) |
0.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio object with concatenated data |
Raises:
| Type | Description |
|---|---|
ValueError
|
If audio metadata doesn't match or crossfade duration is invalid |
Source code in src/videopython/base/audio/audio.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 | |
slice
Extract a portion of the audio between start_seconds and end_seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_seconds
|
float
|
Start time in seconds (default: 0.0) |
0.0
|
end_seconds
|
float | None
|
End time in seconds (default: None, meaning end of audio) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio instance with the extracted portion |
Raises:
| Type | Description |
|---|---|
ValueError
|
If start_seconds or end_seconds are invalid |
Source code in src/videopython/base/audio/audio.py
overlay
Overlay another audio segment on top of this one, mixing both signals. If mixing mono and stereo, converts mono to stereo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Audio
|
Another Audio object to overlay |
required |
position
|
float
|
Start position in seconds for the overlay (default: 0.0) |
0.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Audio |
Audio
|
New Audio object with mixed audio |
Raises:
| Type | Description |
|---|---|
ValueError
|
If audio metadata doesn't match or position is invalid |
Source code in src/videopython/base/audio/audio.py
save
Save audio to a file using ffmpeg
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Path to save the audio file |
required |
format
|
str | None
|
Output format (e.g., 'mp3', 'wav'). If None, inferred from extension. |
None
|
Source code in src/videopython/base/audio/audio.py
__len__
__repr__
String representation of the Audio object
Source code in src/videopython/base/audio/audio.py
get_levels
Calculate audio levels for a segment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_seconds
|
float
|
Start time in seconds (default: 0.0) |
0.0
|
end_seconds
|
float | None
|
End time in seconds (default: None, meaning end of audio) |
None
|
Returns:
| Type | Description |
|---|---|
'AudioLevels'
|
AudioLevels with RMS, peak, and dB measurements |
Example
audio = Audio.from_file("audio.mp3") levels = audio.get_levels() print(f"Peak: {levels.db_peak:.1f} dB")
Source code in src/videopython/base/audio/audio.py
get_levels_over_time
get_levels_over_time(
window_seconds: float = 0.1,
hop_seconds: float | None = None,
) -> list[tuple[float, "AudioLevels"]]
Calculate audio levels over time using a sliding window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_seconds
|
float
|
Window size in seconds (default: 0.1) |
0.1
|
hop_seconds
|
float | None
|
Hop size in seconds (default: window_seconds / 2) |
None
|
Returns:
| Type | Description |
|---|---|
list[tuple[float, 'AudioLevels']]
|
List of (timestamp, AudioLevels) tuples where timestamp is the |
list[tuple[float, 'AudioLevels']]
|
center of each window |
Example
levels_over_time = audio.get_levels_over_time(window_seconds=0.1) for timestamp, levels in levels_over_time: ... print(f"{timestamp:.2f}s: {levels.db_rms:.1f} dB")
Source code in src/videopython/base/audio/audio.py
detect_silence
detect_silence(
threshold_db: float = -40.0,
min_duration: float = 0.5,
window_seconds: float = 0.1,
) -> list["SilentSegment"]
Detect silent segments in the audio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold_db
|
float
|
RMS level below which audio is considered silent (default: -40 dB) |
-40.0
|
min_duration
|
float
|
Minimum duration for a segment to be classified as silent (default: 0.5s) |
0.5
|
window_seconds
|
float
|
Window size for level analysis (default: 0.1s) |
0.1
|
Returns:
| Type | Description |
|---|---|
list['SilentSegment']
|
List of SilentSegment objects representing detected silent regions |
Example
silent_segments = audio.detect_silence(threshold_db=-40.0, min_duration=0.5) for seg in silent_segments: ... print(f"Silence: {seg.start:.2f}s - {seg.end:.2f}s")
Source code in src/videopython/base/audio/audio.py
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 | |
classify_segments
Classify audio segments as speech, music, noise, or silence.
This uses basic signal processing heuristics (no ML): - Zero-crossing rate (higher for speech/noise) - Spectral flatness (higher for noise, lower for music) - Energy distribution across frequency bands
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segment_length
|
float
|
Length of each segment to classify in seconds (default: 2.0) |
2.0
|
overlap
|
float
|
Overlap between segments as fraction (default: 0.5) |
0.5
|
Returns:
| Type | Description |
|---|---|
list['AudioSegment']
|
List of AudioSegment objects with classifications |
Example
segments = audio.classify_segments(segment_length=2.0) for seg in segments: ... print(f"{seg.start:.1f}-{seg.end:.1f}s: {seg.segment_type.value}")
Source code in src/videopython/base/audio/audio.py
normalize
Normalize audio to a target level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_db
|
float
|
Target level in dB (default: -3.0 dB, allows headroom) |
-3.0
|
method
|
str
|
Normalization method, either "peak" or "rms" (default: "peak") |
'peak'
|
Returns:
| Type | Description |
|---|---|
'Audio'
|
New Audio object with normalized levels |
Example
normalized = audio.normalize(target_db=-3.0, method="peak") print(f"New peak: {normalized.get_levels().db_peak:.1f} dB")
Source code in src/videopython/base/audio/audio.py
Audio Analysis
The Audio class includes methods for analyzing audio levels, detecting silence, classifying content, and normalizing.
Level Analysis
from videopython.base import Audio
audio = Audio.from_file("audio.mp3")
# Get overall levels
levels = audio.get_levels()
print(f"Peak: {levels.db_peak:.1f} dB, RMS: {levels.db_rms:.1f} dB")
# Get levels for a specific segment
segment_levels = audio.get_levels(start_seconds=1.0, end_seconds=3.0)
# Get levels over time (sliding window analysis)
levels_over_time = audio.get_levels_over_time(window_seconds=0.1)
for timestamp, levels in levels_over_time:
print(f"{timestamp:.2f}s: {levels.db_rms:.1f} dB")
Silence Detection
from videopython.base import Audio
audio = Audio.from_file("podcast.mp3")
# Detect silent segments
silent_segments = audio.detect_silence(
threshold_db=-40.0, # dB threshold
min_duration=0.5, # minimum silence duration in seconds
)
for seg in silent_segments:
print(f"Silence: {seg.start:.2f}s - {seg.end:.2f}s ({seg.duration:.2f}s)")
Segment Classification
Classify audio segments as speech, music, noise, or silence using heuristic analysis (no ML required).
from videopython.base import Audio
audio = Audio.from_file("mixed_content.mp3")
# Classify 2-second segments with 50% overlap
segments = audio.classify_segments(segment_length=2.0, overlap=0.5)
for seg in segments:
print(f"{seg.start:.1f}-{seg.end:.1f}s: {seg.segment_type.value} ({seg.confidence:.0%})")
Normalization
from videopython.base import Audio
audio = Audio.from_file("quiet_audio.mp3")
# Peak normalization (default)
normalized = audio.normalize(target_db=-3.0, method="peak")
# RMS normalization
normalized = audio.normalize(target_db=-18.0, method="rms")
# Verify
print(f"New peak: {normalized.get_levels().db_peak:.1f} dB")
Data Classes
AudioMetadata
Stores metadata for audio files including sample rate, channels, duration, and frame count.
AudioMetadata
dataclass
Stores metadata for audio files
Source code in src/videopython/base/audio/audio.py
AudioLevels
Audio level measurements (RMS, peak, dB values).
AudioLevels
dataclass
Audio level measurements for a segment.
Attributes:
| Name | Type | Description |
|---|---|---|
rms |
float
|
Root mean square (average loudness), 0.0 to 1.0 |
peak |
float
|
Maximum absolute amplitude, 0.0 to 1.0 |
db_rms |
float
|
RMS level in decibels (relative to full scale) |
db_peak |
float
|
Peak level in decibels (relative to full scale) |
Example
audio = Audio.from_file("audio.mp3") levels = audio.get_levels() print(f"Peak: {levels.db_peak:.1f} dB, RMS: {levels.db_rms:.1f} dB")
Source code in src/videopython/base/audio/analysis.py
SilentSegment
Represents a detected silent segment with timestamps.
SilentSegment
dataclass
Represents a detected silent segment.
Attributes:
| Name | Type | Description |
|---|---|---|
start |
float
|
Start time in seconds |
end |
float
|
End time in seconds |
duration |
float
|
Duration in seconds |
avg_level |
float
|
Average RMS level during the segment |
Example
silent_segments = audio.detect_silence(threshold_db=-40.0) for seg in silent_segments: ... print(f"Silence: {seg.start:.2f}s - {seg.end:.2f}s ({seg.duration:.2f}s)")
Source code in src/videopython/base/audio/analysis.py
AudioSegment
A classified segment of audio with type and confidence.
AudioSegment
dataclass
A classified segment of audio.
Attributes:
| Name | Type | Description |
|---|---|---|
start |
float
|
Start time in seconds |
end |
float
|
End time in seconds |
segment_type |
AudioSegmentType
|
Classification of the segment content |
confidence |
float
|
Confidence score for the classification (0.0 to 1.0) |
levels |
AudioLevels
|
Audio level measurements for the segment |
Example
segments = audio.classify_segments(segment_length=2.0) for seg in segments: ... print(f"{seg.start:.1f}-{seg.end:.1f}s: {seg.segment_type.value} ({seg.confidence:.0%})")
Source code in src/videopython/base/audio/analysis.py
AudioSegmentType
Enum for audio segment classification: SILENCE, SPEECH, MUSIC, NOISE.
AudioSegmentType
Exceptions
AudioLoadError
Exception raised when there's an error loading or saving audio files.