Skip to main content

Overview

The FlacEncoder class provides utilities for re-encoding FLAC audio files to a standardized format (24-bit, 48kHz) while preserving metadata and cover art. It supports both ffmpeg and native flac encoders.

Dependencies

Requires one of the following system tools:
  • ffmpeg (recommended) - Install via package manager
  • flac - Native FLAC encoder
# Ubuntu/Debian
sudo apt install ffmpeg

# macOS
brew install ffmpeg

# Windows (using Chocolatey)
choco install ffmpeg

Import

from tagqt.core.flac import FlacEncoder, DependencyChecker

FlacEncoder Methods

is_flac_available

Checks if the native flac encoder is installed.
@staticmethod
def is_flac_available() -> bool
Returns: True if flac command is available, False otherwise Example:
if FlacEncoder.is_flac_available():
    print("FLAC encoder is installed")
else:
    print("FLAC encoder not found")

is_ffmpeg_available

Checks if ffmpeg is installed.
@staticmethod
def is_ffmpeg_available() -> bool
Returns: True if ffmpeg command is available, False otherwise Example:
if FlacEncoder.is_ffmpeg_available():
    print("ffmpeg is installed")
else:
    print("ffmpeg not found")

get_available_encoder

Returns the name of the first available encoder, preferring flac over ffmpeg.
@staticmethod
def get_available_encoder() -> str | None
Returns: 'flac', 'ffmpeg', or None if neither is available Example:
encoder = FlacEncoder.get_available_encoder()
if encoder:
    print(f"Using encoder: {encoder}")
else:
    print("No encoder available. Please install ffmpeg or flac.")

reencode_flac

Re-encodes a FLAC file to 24-bit, 48kHz format while preserving metadata and cover art.
@staticmethod
def reencode_flac(filepath: str) -> tuple[bool, str | None]
filepath
str
required
Path to the FLAC file to re-encode
Returns: Tuple of (success: bool, error_message: str | None)
  • (True, None) on success
  • (False, error_message) on failure
Encoding Parameters:
  • Sample format: 24-bit (s32)
  • Sample rate: 48000 Hz
  • Compression level: 5 (balanced)
  • Metadata: Preserved from original
  • Cover art: Preserved from original
Example:
success, error = FlacEncoder.reencode_flac("/path/to/audio.flac")

if success:
    print("Re-encoding completed successfully")
else:
    print(f"Re-encoding failed: {error}")
Batch Processing Example:
import os
from tagqt.core.flac import FlacEncoder

def reencode_directory(directory):
    """Re-encode all FLAC files in a directory."""
    if not FlacEncoder.get_available_encoder():
        print("Error: No encoder available")
        return
    
    for filename in os.listdir(directory):
        if filename.lower().endswith('.flac'):
            filepath = os.path.join(directory, filename)
            print(f"Processing: {filename}")
            
            success, error = FlacEncoder.reencode_flac(filepath)
            
            if success:
                print(f"  ✓ Success")
            else:
                print(f"  ✗ Failed: {error}")

# Usage
reencode_directory("/path/to/music")

DependencyChecker Methods

check_koroman

Checks if the koroman library is installed.
@staticmethod
def check_koroman() -> tuple[bool, str | None]
Returns: Tuple of (is_installed: bool, message: str | None)
  • (True, None) if installed
  • (False, error_message) if not installed
Example:
installed, message = DependencyChecker.check_koroman()

if not installed:
    print(message)  # "koroman library is not installed. Install with: pip install koroman"

check_flac_tools

Checks if FLAC encoding tools are available and returns which encoder is found.
@staticmethod
def check_flac_tools() -> tuple[bool, str]
Returns: Tuple of (is_available: bool, encoder_name_or_error: str)
  • (True, 'flac') or (True, 'ffmpeg') if available
  • (False, error_message) if neither is available
Example:
available, result = DependencyChecker.check_flac_tools()

if available:
    print(f"Encoder available: {result}")
else:
    print(result)  # "Neither flac nor ffmpeg is installed. Please install one of them."

Complete Usage Example

from tagqt.core.flac import FlacEncoder, DependencyChecker

# Check dependencies
available, encoder = DependencyChecker.check_flac_tools()

if not available:
    print(encoder)  # Error message
    exit(1)

print(f"Using encoder: {encoder}")

# Re-encode a file
filepath = "/path/to/audio.flac"
success, error = FlacEncoder.reencode_flac(filepath)

if success:
    print("File re-encoded to 24-bit/48kHz successfully")
    print("All metadata and cover art preserved")
else:
    print(f"Encoding failed: {error}")

Technical Details

Metadata Preservation

The encoder preserves all standard metadata fields:
  • title, artist, album, year, genre
  • track_number, disc_number, album_artist
  • comment, lyrics, bpm, initial_key
  • isrc, publisher
  • Cover art (album artwork)

ffmpeg Command

The encoder uses the following ffmpeg command structure:
ffmpeg -y -i input.flac \
  -map_metadata 0 \
  -c:a flac \
  -compression_level 5 \
  -sample_fmt s32 \
  -ar 48000 \
  -c:v copy \
  output.flac

Notes

  • All methods are static and do not require instantiation
  • Original files are replaced after successful re-encoding
  • Temporary files are used during encoding and cleaned up automatically
  • Metadata is explicitly restored after encoding to ensure no data loss
  • Only .flac files are processed; other formats return an error
  • The encoder preference order is: flacffmpegNone

Build docs developers (and LLMs) love