G.711 μ-law Encoder (Run)

This article explains how you can use Transcoder.run to encode a WAV file to G.711 μ-law compressed audio format.

The code snippets in this article are from the enc_g711_ulaw_file sample.

Source Audio

For source we use the express-dictate_8000_s16_1ch_pcm.wav file from the AVBlocks Assets repository. After downloading and unzipping you will find express-dictate_8000_s16_1ch_pcm.wav in the aud subdirectory.

Code

This code takes a WAV file and encodes it to compressed G.711 μ-law format.

Initialize AVBlocks

The first step in any AVBlocks application is to initialize the library. This must be done before using any other AVBlocks functionality. The Library.initialize() method sets up the internal state and loads necessary codecs. Always remember to call Library.shutdown() at the end of your program to properly clean up resources and release any allocated memory.

Library.initialize()

# Set license information. Without this AVBlocks runs in Demo mode.
# Library.set_license("<license-string>")

result = encode(input_file, output_file)

Library.shutdown()

sys.exit(0 if result else 2)

Configure Output Socket

The output socket defines where and how the encoded audio data will be written. In this case, we’re configuring it to output a G.711 μ-law WAV file. The socket represents the output destination, while the pin represents the specific audio stream within that destination. The AudioStreamInfo object specifies the audio format parameters - G.711 μ-law typically uses 8000 Hz sample rate and mono channel, which are set explicitly in this example.

def create_output_socket(output_file: str) -> MediaSocket:
    """Create output socket for G.711 μ-law WAV file."""
    socket = MediaSocket()
    socket.file = output_file
    socket.stream_type = StreamType.WAVE

    pin = MediaPin()
    socket.pins.add(pin)

    asi = AudioStreamInfo()
    pin.stream_info = asi

    asi.stream_type = StreamType.MULAW_PCM
    # G.711 μ-law typically uses 8000 Hz sample rate and mono channel
    asi.sample_rate = 8000
    asi.channels = 1

    return socket

Configure Transcoder and Encode

This is the main encoding function that ties everything together. First, we create an input socket that points to the WAV file we want to encode. Then we create the output socket using our helper method. The transcoder is the core component that performs the actual encoding - it takes the uncompressed PCM data from the input and converts it to compressed G.711 μ-law data for the output.

The allow_demo_mode = True setting allows the transcoder to work even without a valid license (useful for testing, but not recommended for production). We then add our input and output sockets to the transcoder, open it to prepare for processing, run the actual transcoding operation, and finally close it to clean up.

def encode(input_file: str, output_file: str) -> bool:
    """Encode WAV file to G.711 μ-law."""
    # Transcoder will fail if output exists (by design)
    delete_file(output_file)

    # Create output directory if it doesn't exist
    output_dir = os.path.dirname(output_file)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Create input socket
    in_socket = MediaSocket()
    in_socket.file = input_file

    # Create output socket
    out_socket = create_output_socket(output_file)

    # Create transcoder
    with Transcoder() as transcoder:
        transcoder.allow_demo_mode = True
        transcoder.inputs.add(in_socket)
        transcoder.outputs.add(out_socket)

        res = transcoder.open()
        print_error("Transcoder open", transcoder.error)
        if not res:
            return False

        res = transcoder.run()
        print_error("Transcoder run", transcoder.error)
        if not res:
            return False

        transcoder.close()

    return True

Complete Python Code

Here’s the complete working example that demonstrates G.711 μ-law encoding using AVBlocks. This code combines all the previous snippets into a functional program that can be run. The main function handles command-line argument parsing, initializes AVBlocks, performs the encoding operation, and properly shuts down the library before exiting.

"""
Encode WAV file to G.711 μ-law.

This sample encodes a WAV audio file to G.711 μ-law format using AVBlocks.
"""

import os
import sys
import click

from avblocks import (
    Library, Transcoder, MediaSocket, MediaPin,
    AudioStreamInfo, StreamType, ErrorFacility
)


def delete_file(filename: str):
    """Delete a file if it exists."""
    try:
        if os.path.exists(filename):
            os.remove(filename)
    except OSError:
        pass


def print_error(action: str, error) -> None:
    """Print error information."""
    if action:
        print(f"{action}: ", end="")

    if error.facility == ErrorFacility.Success:
        print("Success")
        return

    print(f"{error.message or ''}, facility:{error.facility} code:{error.code} hint:{error.hint or ''}")


def create_output_socket(output_file: str) -> MediaSocket:
    """Create output socket for G.711 μ-law WAV file."""
    socket = MediaSocket()
    socket.file = output_file
    socket.stream_type = StreamType.WAVE

    pin = MediaPin()
    socket.pins.add(pin)

    asi = AudioStreamInfo()
    pin.stream_info = asi

    asi.stream_type = StreamType.MULAW_PCM
    # G.711 μ-law typically uses 8000 Hz sample rate and mono channel
    asi.sample_rate = 8000
    asi.channels = 1

    return socket


def encode(input_file: str, output_file: str) -> bool:
    """Encode WAV file to G.711 μ-law."""
    # Transcoder will fail if output exists (by design)
    delete_file(output_file)

    # Create output directory if it doesn't exist
    output_dir = os.path.dirname(output_file)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Create input socket
    in_socket = MediaSocket()
    in_socket.file = input_file

    # Create output socket
    out_socket = create_output_socket(output_file)

    # Create transcoder
    with Transcoder() as transcoder:
        transcoder.allow_demo_mode = True
        transcoder.inputs.add(in_socket)
        transcoder.outputs.add(out_socket)

        res = transcoder.open()
        print_error("Transcoder open", transcoder.error)
        if not res:
            return False

        res = transcoder.run()
        print_error("Transcoder run", transcoder.error)
        if not res:
            return False

        transcoder.close()

    return True


@click.command()
@click.option('-i', '--input', 'input_file',
              help='Input WAV file (PCM)',
              type=click.Path(exists=True))
@click.option('-o', '--output', 'output_file',
              help='Output WAV file (G.711 μ-law)',
              type=click.Path())
def main(input_file: str, output_file: str):
    """Encode WAV file to G.711 μ-law."""

    # Set default options if not provided
    if not input_file or not output_file:
        script_dir = os.path.dirname(os.path.abspath(__file__))

        if not input_file:
            input_file = os.path.join(script_dir, "../../assets/aud/8k16bitpcm.wav")
        if not output_file:
            output_file = os.path.join(script_dir, "../../output/enc_g711_ulaw_file/8k_ulaw.wav")

        print("Using default options:")
        print(f"  --input {input_file}")
        print(f"  --output {output_file}")
        print()

    # Validate options
    print(f"--input: {input_file}")
    print(f"--output: {output_file}")

    Library.initialize()

    # Set license information. Without this AVBlocks runs in Demo mode.
    # Library.set_license("<license-string>")

    result = encode(input_file, output_file)

    Library.shutdown()

    sys.exit(0 if result else 2)


if __name__ == '__main__':
    main()

How to Run

See the Python sample for details. The samples are installed as command-line tools when you install the package from the repository root with uv pip install --editable . (see Installation).

Command Line

enc-g711-ulaw-file --input <wav file> --output <g711 ulaw wav file>

Examples

List options:

enc-g711-ulaw-file --help
Usage: enc-g711-ulaw-file [OPTIONS]

  Encode WAV file to G.711 μ-law.

Options:
  -i, --input PATH   Input WAV file (PCM)
  -o, --output PATH  Output WAV file (G.711 μ-law)
  --help             Show this message and exit.

Encode the input file ./assets/aud/express-dictate_8000_s16_1ch_pcm.wav into output file ./output/enc_g711_ulaw_file/express-dictate_g711_ulaw.wav:

# Linux and macOS
mkdir -p ./output/enc_g711_ulaw_file

enc-g711-ulaw-file \
    --input ./assets/aud/express-dictate_8000_s16_1ch_pcm.wav \
    --output ./output/enc_g711_ulaw_file/express-dictate_g711_ulaw.wav
# Windows
New-Item -ItemType Directory -Force -Path ./output/enc_g711_ulaw_file

enc-g711-ulaw-file `
    --input ./assets/aud/express-dictate_8000_s16_1ch_pcm.wav `
    --output ./output/enc_g711_ulaw_file/express-dictate_g711_ulaw.wav