What is μ-law (Mu-law) Audio Encoding?

The complete technical guide to G.711 μ-law for voice AI, telephony and VoIP — covering the compression formula, code implementations in Python, JavaScript and C, provider comparison, setup guides and troubleshooting.

G.711 PCMU Standard Voice AI & Telephony Python / JS / C Code 8 kHz • 8-bit • 64 kbps

What is μ-law (Mu-law)?

μ-law (mu-law) is a companding algorithm defined in ITU-T Recommendation G.711 that compresses 16-bit linear PCM audio into 8-bit logarithmic values. It is the standard audio codec for telephone networks in North America and Japan, and is widely used in VoIP, SIP and modern voice AI systems.

Key concept: μ-law compresses the dynamic range of audio by applying logarithmic encoding — providing better signal-to-noise ratio for quieter sounds while maintaining acceptable quality for louder signals. This gives approximately 13-bit dynamic range in an 8-bit format.

Why μ-law Matters in Voice AI

  • Bandwidth efficiency — reduces audio data from 16-bit to 8-bit per sample (50% reduction)
  • Telephony compatibility — standard format for PSTN networks and SIP trunks
  • Real-time processing — near-zero latency encoding and decoding
  • Voice quality — optimised for human speech frequencies (300–3,400 Hz)
  • Universal support — every telephony platform, PBX and VoIP gateway supports it

Historical Context

Developed in the 1960s for digital telephony, μ-law became the standard companding algorithm for T1 carrier systems in North America. Today it remains essential in VoIP, SIP protocols and modern voice AI — including systems like the Team-Connect AI Receptionist that handle thousands of UK business calls daily.

How μ-law Works

The μ-law Compression Formula

F(x) = sgn(x) × ln(1 + μ|x|) / ln(1 + μ)

Where x is the input sample (−1 ≤ x ≤ 1), μ is the compression parameter (255 for G.711), sgn(x) is the sign function, and ln is the natural logarithm.

Step-by-Step Process

1

Input Linear PCM

Start with a 16-bit linear PCM audio sample (range: −32,768 to +32,767)

2

Normalise Sample

Convert to normalised range (−1.0 to +1.0) by dividing by 32,768

3

Apply μ-law Compression

Use the formula with μ = 255 to compress the dynamic range logarithmically

4

Quantise to 8-bit

Map the compressed value to an 8-bit representation (0–255)

5

Add Sign Bit

Encode sign information in the MSB (most significant bit)

Dynamic range optimisation: μ-law allocates more quantisation levels to smaller amplitude signals where human hearing is most sensitive, giving approximately 13-bit dynamic range in an 8-bit format.

G.711 μ-law Technical Specifications

ParameterValue
StandardITU-T G.711
Codec namePCMU (Pulse Code Modulation μ-law)
Sample rate8,000 Hz
Bit depth8 bits per sample
Bit rate64 kbps
Compression parameter (μ)255
Dynamic range~78 dB (≈13-bit equivalent)
Frequency range300–3,400 Hz
Frame sizeTypically 20 ms (160 samples)
RTP payload type0 (RFC 3551)
SDP codec namePCMU/8000
Encoding latency~0.15 ms (near-zero)
CPU usageNegligible (<1%)
Primary regionsNorth America, Japan

Code Examples — Python, JavaScript and C

Python μ-law Encoder

Python
import numpy as np def mu_law_encode(signal, mu=255): """Encode linear PCM signal using μ-law compression""" signal = np.clip(signal, -1.0, 1.0) compressed = np.sign(signal) * np.log(1 + mu * np.abs(signal)) / np.log(1 + mu) quantized = ((compressed + 1) / 2 * 255).astype(np.uint8) return quantized # Example linear_pcm = np.array([-0.8, -0.4, 0.0, 0.4, 0.8]) encoded = mu_law_encode(linear_pcm) print(f"Linear PCM: {linear_pcm}") print(f"μ-law Encoded: {encoded}")

Python μ-law Decoder

Python
def mu_law_decode(encoded, mu=255): """Decode μ-law compressed signal back to linear PCM""" normalized = (encoded.astype(float) / 255) * 2 - 1 decoded = np.sign(normalized) * ((1 + mu) ** np.abs(normalized) - 1) / mu return decoded mulaw_values = np.array([15, 95, 127, 159, 239]) linear_decoded = mu_law_decode(mulaw_values) print(f"μ-law Encoded: {mulaw_values}") print(f"Linear Decoded: {linear_decoded}")

JavaScript Implementation

JavaScript
class MuLawCodec { constructor(mu = 255) { this.mu = mu; this.bias = 0x84; this.clip = 32635; } encode(linearValue) { let sign = (linearValue >> 8) & 0x80; if (sign !== 0) linearValue = -linearValue; if (linearValue > this.clip) linearValue = this.clip; linearValue += this.bias; let exponent = this.findExponent(linearValue); let mantissa = (linearValue >> (exponent + 3)) & 0x0F; return ~(sign | (exponent << 4) | mantissa) & 0xFF; } decode(mulawValue) { mulawValue = ~mulawValue; let sign = mulawValue & 0x80; let exponent = (mulawValue >> 4) & 0x07; let mantissa = mulawValue & 0x0F; let linear = ((mantissa << 3) + this.bias) << (exponent + 1); linear -= this.bias; return sign !== 0 ? -linear : linear; } findExponent(value) { let exp = 0; value >>= 8; while (value > 0 && exp < 7) { value >>= 1; exp++; } return exp; } } const codec = new MuLawCodec(); console.log(codec.encode(16384)); // Encode console.log(codec.decode(170)); // Decode

Optimised C Implementation

C
#include <stdint.h> static const uint8_t mulaw_encode_table[256] = { 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, // ... (complete 256-entry lookup table) }; uint8_t mulaw_encode_fast(int16_t pcm) { uint8_t sign = (pcm >> 8) & 0x80; if (sign) pcm = -pcm; if (pcm > 32635) pcm = 32635; pcm += 0x84; uint8_t exp = mulaw_encode_table[(pcm >> 7) & 0xFF]; uint8_t man = (pcm >> (exp + 3)) & 0x0F; return ~(sign | (exp << 4) | man); } // Batch processing void process_batch(int16_t* in, uint8_t* out, size_t n) { for (size_t i = 0; i < n; i++) out[i] = mulaw_encode_fast(in[i]); }
Implementation note: Production G.711 implementations use lookup tables rather than computing logarithms at runtime. Pre-computed tables for both encoding and decoding give consistent sub-microsecond performance.

Implementation in Voice AI Systems

WebRTC Integration

WebRTC μ-law Config
const pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }); const transceivers = pc.getTransceivers(); transceivers.forEach(t => { if (t.sender?.track?.kind === 'audio') { const codecs = RTCRtpSender.getCapabilities('audio').codecs; const pcmu = codecs.find(c => c.mimeType === 'audio/PCMU'); if (pcmu) t.setCodecPreferences([pcmu]); } });

SIP / SDP Configuration

SDP for μ-law
v=0 o=- 0 0 IN IP4 192.168.1.100 s=VoiceAI Session c=IN IP4 192.168.1.100 t=0 0 m=audio 5004 RTP/AVP 0 a=rtpmap:0 PCMU/8000 a=ptime:20 a=sendrecv

Performance Optimisation Tips

  • Lookup tables — pre-computed tables instead of runtime logarithms
  • SIMD instructions — leverage vectorisation for batch processing
  • Circular buffers — for streaming audio without allocation overhead
  • Dedicated threads — separate encode/decode from application logic
  • Pre-allocated memory — avoid malloc in the audio processing loop

μ-law Providers & Platforms

Major cloud and telephony platforms that support G.711 μ-law for voice AI and communications:

Twilio
Leading CPaaS with comprehensive μ-law support for voice applications
  • Voice API with μ-law codec
  • Real-time media streaming
  • WebRTC integration
Documentation →
Amazon Connect
Cloud contact centre with μ-law telephony integration
  • Chime SDK Voice
  • Kinesis Video Streams
  • Transcribe real-time
Documentation →
Google Cloud
Speech-to-Text and Contact Centre AI with μ-law processing
  • Speech-to-Text API
  • Dialogflow CX
  • Contact Centre AI
Documentation →
Microsoft Azure
Communication Services with μ-law support
  • Azure Comm Services
  • Speech SDK
  • Bot Framework
Documentation →
FreeSWITCH
Open-source telephony with native μ-law processing
  • Native G.711 codec
  • Real-time transcoding
  • WebRTC gateway
Documentation →
Asterisk
Popular open-source PBX with μ-law codec support
  • Built-in μ-law codec
  • SIP/IAX2 protocols
  • ARI interface
Documentation →
Team-Connect
AI voice receptionist with optimised μ-law processing for UK businesses
  • Native μ-law support
  • AI voice recognition
  • Real-time transcription
Learn More →
Vonage API
Communications API with μ-law codec for voice apps
  • Voice API
  • WebSocket streaming
  • Global carrier network
Documentation →

Complete μ-law Setup Guide

1. Environment Setup

Dependencies
# Python pip install numpy scipy soundfile pyaudio # Node.js npm install node-webrtc ws audiobuffer-to-wav # System libraries (Ubuntu/Debian) sudo apt-get install libasound2-dev portaudio19-dev

2. Audio Input Configuration

Python Audio Input
import pyaudio CHUNK = 160 # 20ms at 8kHz FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 8000 audio = pyaudio.PyAudio() stream = audio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK )

3. Full μ-law Processor Class

Python MuLawProcessor
import numpy as np class MuLawProcessor: def __init__(self): self.mu = 255 def encode_buffer(self, pcm_data): """Encode PCM buffer to μ-law""" samples = np.frombuffer(pcm_data, dtype=np.int16) normalized = samples.astype(np.float32) / 32768.0 sign = np.sign(normalized) abs_val = np.abs(normalized) compressed = sign * np.log(1 + self.mu * abs_val) / np.log(1 + self.mu) quantized = ((compressed + 1) / 2 * 255).astype(np.uint8) return quantized.tobytes() def decode_buffer(self, mulaw_data): """Decode μ-law buffer to PCM""" encoded = np.frombuffer(mulaw_data, dtype=np.uint8) normalized = (encoded.astype(np.float32) / 255) * 2 - 1 sign = np.sign(normalized) abs_val = np.abs(normalized) expanded = sign * ((1 + self.mu) ** abs_val - 1) / self.mu pcm = (expanded * 32768).astype(np.int16) return pcm.tobytes()

4. Real-Time Processing Loop

Processing Loop
processor = MuLawProcessor() try: while True: pcm_data = stream.read(CHUNK) mulaw_data = processor.encode_buffer(pcm_data) # Send to voice AI service via WebSocket ws.send(mulaw_data) except KeyboardInterrupt: stream.stop_stream() stream.close() audio.terminate()

Common Issues & Troubleshooting

1. Distorted or Poor Quality Audio

Symptoms: Crackling, hiss or muffled sound in decoded audio.

Causes: Incorrect sample rate conversion, clipping in input signal, wrong μ parameter, bit depth mismatch.

Fixes: Ensure input is normalised to [−1, 1]. Use anti-aliasing filter when downsampling. Verify μ = 255 for G.711. Check sign bit handling.

2. High Processing Latency

Symptoms: Delay in real-time audio processing.

Causes: Large buffer sizes, inefficient encoding, memory allocation in audio loop.

Fixes: Use 160-sample buffers (20 ms). Implement lookup table encoding. Pre-allocate buffers. Use real-time thread priority.

3. Codec Compatibility Issues

Symptoms: Audio not playing or recognised by other systems.

Causes: Non-standard implementation, incorrect RTP payload, wrong SDP negotiation, endianness issues.

Fixes: Follow ITU-T G.711 exactly. Use RTP payload type 0. Implement proper SDP negotiation. Test with reference implementations.

Debugging Tools

Quick Validation Script
import numpy as np processor = MuLawProcessor() test_values = [0, 127, 255, -32768, 32767, 1000, -1000] print("Original\tEncoded\tDecoded\tError") for val in test_values: pcm = np.array([val], dtype=np.int16).tobytes() enc = processor.encode_buffer(pcm) dec = np.frombuffer(processor.decode_buffer(enc), dtype=np.int16)[0] print(f"{val:8d}\t{enc[0]:7d}\t{dec:7d}\t{abs(val - dec):5d}")

μ-law vs Other Audio Codecs

CodecBit RateSample RateQualityLatencyUse Case
μ-law (G.711)64 kbps8 kHzGoodVery LowTelephony, VoIP
A-law (G.711)64 kbps8 kHzGoodVery LowEuropean telephony
G.72264 kbps16 kHzVery GoodLowHD Voice
G.7298 kbps8 kHzGoodMediumLow bandwidth VoIP
Opus6–510 kbps8–48 kHzExcellentLowWebRTC, modern VoIP
PCM (16-bit)128 kbps8 kHzExcellentVery LowUncompressed

When to Choose μ-law

μ-law is ideal for: Legacy telephony / PSTN integration, real-time applications needing minimal latency, resource-constrained environments, standardised voice quality across networks, and simple implementation with easy debugging.
Consider alternatives when: You need high-fidelity audio (use Opus), very low bandwidth (use G.729), wideband / HD voice (use G.722 or Opus), or modern WebRTC-only applications (Opus provides better quality and flexibility).

Performance Benchmarks

Benchmark Results
Processing 1 second of audio (8,000 samples): μ-law Encoding: 0.15 ms | CPU: <1% | Memory: 16 KB μ-law Decoding: 0.12 ms | CPU: <1% | Memory: 16 KB Encoding 1 second comparison: μ-law: 0.15 ms G.729: 25.30 ms Opus: 3.20 ms AAC-LC: 8.70 ms MOS Quality Scores: μ-law: 3.2–3.8 G.722: 4.0–4.5 Opus: 4.2–4.7 PCM: 4.8–5.0

μ-law Audio Encoding — 8 FAQs Answered

What is μ-law audio encoding?

μ-law is a companding algorithm (G.711) that compresses 16-bit PCM to 8-bit logarithmic values. Standard codec for telephone networks in North America and Japan, widely used in VoIP and voice AI.

What is the difference between μ-law and A-law?

μ-law (PCMU) is North America/Japan standard. A-law (PCMA) is Europe/rest of world. Both compress 16-bit to 8-bit with slightly different curves. μ-law has marginally better SNR at low levels.

Why is μ-law used in voice AI systems?

Near-zero latency, 50% bandwidth reduction, universal telephony compatibility, optimised for speech frequencies, and negligible CPU usage — ideal for real-time voice AI.

What sample rate and bit rate does μ-law use?

8 kHz sample rate, 8-bit samples, constant 64 kbps bitrate. Matches the 300–3,400 Hz bandwidth of traditional telephone networks.

Which providers support μ-law?

Twilio, Amazon Connect, Google Cloud STT, Azure Communication Services, FreeSWITCH, Asterisk, Vonage and Team-Connect all support G.711 μ-law (PCMU).

Is μ-law better than Opus for voice AI?

Depends on the use case. μ-law has near-zero latency and universal PSTN/SIP compatibility. Opus has better quality and compression but slightly higher complexity — better for WebRTC-only systems.

What is the RTP payload type for μ-law?

RTP payload type 0, defined in RFC 3551. This is the default audio codec for most SIP and RTP implementations.

How do I debug μ-law audio quality issues?

Check input normalisation (must be [−1, 1]), verify μ = 255, test with known reference signals, validate round-trip encode/decode, and check for sample rate mismatches between source and codec.

Building a voice AI system? The Team-Connect AI Receptionist uses optimised μ-law processing to handle thousands of UK business calls daily. Try it free.