yb.audio_convert¶
Convert audio files between formats with ffmpeg.
Audio arrives in whatever format the source offers — YouTube’s best audio is
typically Opus in a .webm container — which is usually fine to keep as is.
Publishing paths, though, often want something specific: .mp3 for podcast
players, .wav for editing. convert_audio() is the one-call bridge:
>>> from yb.audio_convert import convert_audio
>>> convert_audio("talk.webm", "mp3")
PosixPath('talk.mp3')
Conversion is a no-op when the source is already in the target format, so it is safe to call unconditionally:
>>> convert_audio("talk.mp3", "mp3")
PosixPath('talk.mp3')
Requires ffmpeg on PATH; without it AudioConversionError is
raised (see also the on_error="warn" escape hatch in
yb.download.download_youtube_audio()).
Module Attributes
Formats that store samples losslessly — a target bitrate is meaningless there. |
|
Bitrate applied to lossy targets when the caller doesn't specify one. |
Functions
|
Convert |
|
Normalize a format spec to a bare lowercase extension. |
Exceptions
Raised when audio could not be converted to the requested format. |
- exception yb.audio_convert.AudioConversionError[source]¶
Bases:
RuntimeErrorRaised when audio could not be converted to the requested format.
- yb.audio_convert.DEFAULT_LOSSY_BITRATE = '192k'¶
Bitrate applied to lossy targets when the caller doesn’t specify one.
- yb.audio_convert.LOSSLESS_FORMATS = frozenset({'aif', 'aiff', 'alac', 'flac', 'wav'})¶
Formats that store samples losslessly — a target bitrate is meaningless there.
- yb.audio_convert.convert_audio(src, audio_format, *, output=None, bitrate=None, overwrite=True, extra_ffmpeg_args=())[source]¶
Convert
srctoaudio_format, returning the resulting path.- Parameters:
audio_format (
str) – Target format as an extension ("mp3",".wav", …).output (
str|Path|None) – Destination path. Defaults tosrcwith the new extension.bitrate (
str|None) – Target bitrate for lossy formats (e.g."320k"). Defaults toDEFAULT_LOSSY_BITRATE; ignored forLOSSLESS_FORMATS.overwrite (
bool) – Overwriteoutputif it already exists.extra_ffmpeg_args (
Iterable[str]) – Raw ffmpeg arguments, appended last so they win.
- Return type:
- Returns:
The converted file’s path — or
srcunchanged when it is already in the target format (no pointless re-encode, no generation loss).- Raises:
FileNotFoundError – If
srcdoes not exist.AudioConversionError – If ffmpeg is missing, or the conversion fails.