torchaudio (Maintenance) & TorchCodec

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Audio and video work in PyTorch is split between two libraries with very different status. torchaudio offers signal-processing transforms, functional operators, models and pre-trained pipelines, but it has been in a maintenance phase since version 2.8. TorchCodec is the actively developed library for decoding and encoding audio, video and images. This page explains what each one is for in 2026, how to move code written for older torchaudio releases, and what to use for the common tasks: loading audio, computing a mel spectrogram, resampling, augmenting, running a pre-trained speech model, and sampling clips from video.

Examples target Python 3.13 and PyTorch 2.15. The current releases are torchaudio 2.11.1 (2026-10-28), whose README says it works with torch 2.11 and future torch releases, and TorchCodec 0.17.0 (2026-09-30). The torchaudio examples were run on Python 3.13 with PyTorch 2.15, torchaudio 2.11.1 and TorchCodec 0.17.0 (CPU) on 2026-10-31. The TorchCodec decoding and encoding examples (and the dataset that uses AudioDecoder) need the FFmpeg shared libraries, which were not installed, so they were not executed: without FFmpeg, TorchCodec raises RuntimeError: Could not load libtorchcodec. Related pages: torchvision, Tensors, Datasets & DataLoader and, for speech models outside PyTorch, Speech Models.

torchaudio is in maintenance

The torchaudio README and documentation state that the project transitioned into a maintenance phase starting with version 2.8, to reduce overlap with the rest of the PyTorch ecosystem and keep the library focused on processing audio data for machine learning. Some user-facing features were deprecated in 2.8 and removed in 2.9. The community announcement (https://github.com/pytorch/audio/issues/3902) gives the details; from it:

Area Status (2026-10-30)

torchaudio.transforms, torchaudio.functional, torchaudio.compliance.kaldi, torchaudio.models, torchaudio.pipelines

Kept. The maintainers identified these as the most popular parts.

lfilter, RNNTLoss, CUCTC, forced_align, overdrive

Kept after user feedback (they were first planned for deprecation) and ported to PyTorch’s stable ABI; the C++ and CUDA extensions are staying.

Audio and video decoding and encoding

Moved to TorchCodec. Deprecated in 2.8, removed in 2.9.

torchaudio.load and torchaudio.save

Remain, but are implemented on top of the load_with_torchcodec and save_with_torchcodec functions added in 2.8. Most users only need to install torchcodec.

Two practical consequences. First, new feature work will not land in torchaudio: treat it as a stable toolbox of spectrogram transforms and a few model bundles, not as an evolving framework. Second, torchaudio was dropped from the main PyTorch install instructions in 2.8, so it is no longer pulled in by the install selector; add it yourself when you need it.

The announcement is a statement of intent made in August 2025 and updated since; the version in which each item was finally removed is documented there and in the release notes (https://github.com/pytorch/audio/releases), which the reader should check before relying on a specific old API. Caveats reported in that discussion at the time: TorchCodec did not yet support Windows in August 2025, and a user reported that ROCm wheels were unavailable. The current TorchCodec README (checked 2026-10-30) lists CPU wheels for Windows, so re-check both claims for your platform.

pip install torch torchaudio torchcodec
python -c "import torchaudio; print(torchaudio.__version__)"

What older books and tutorials get wrong

Older code (before torchaudio 2.8) Now

torchaudio.load / save with sox or soundfile backends, torchaudio.set_audio_backend, torchaudio.sox_effects

The sox and soundfile backends were removed in 2.9: in torchaudio 2.11.1 set_audio_backend and sox_effects no longer exist, and load / save remain only as wrappers around load_with_torchcodec / save_with_torchcodec. Use TorchCodec AudioDecoder / AudioEncoder, or load / save with torchcodec installed.

torchaudio.info, torchaudio.io.StreamReader / StreamWriter

Removed: torchaudio 2.11.1 has neither info nor the torchaudio.io module. Use the metadata of a TorchCodec decoder and AudioDecoder / VideoDecoder / AudioEncoder.

installing torchaudio from the PyTorch selector

Install it separately with pip install torchaudio if you need transforms or pipelines.

The first row is the most common source of breakage. If a tutorial begins with waveform, sr = torchaudio.load("x.wav") it can still work (the function remains), but the backend selection code around it no longer applies.

TorchCodec: decoding and encoding

TorchCodec is a PyTorch-native library for decoding and encoding video, audio and images on CPU and on CUDA GPUs. It uses the FFmpeg installed on your system for video and audio; FFmpeg is optional if you only decode or encode images. The README states support for FFmpeg major versions 4 to 9 and recommends shared-library builds, especially on Windows. Wheels:

  • Linux x86 and aarch64: the default wheels from PyPI are CUDA-enabled; for another CUDA version use the matching --index-url (the README gives a cu130 example), and for CPU-only use pip install torchcodec --index-url=https://download.pytorch.org/whl/cpu.

  • macOS and Windows: CPU-only wheels. Windows users need --index-url for CUDA support.

  • Intel GPUs (XPU) need the separate torchcodec-xpu plugin.

Each TorchCodec release works with specific torch versions. At the time of checking, the README table listed releases 0.14 to 0.17 as needing torch 2.11 or newer with Python 3.10 to 3.14. Install torch and torchcodec together and consult the table when you pin versions. The low-level decoding APIs are labelled beta on the documentation home page, so signatures may change between releases; the docs home page is for TorchCodec 0.17.

# FFmpeg first (Linux/macOS examples); optional for image-only use
sudo apt-get install ffmpeg        # or: brew install ffmpeg
pip install torch torchcodec

Decoding audio

from torchcodec.decoders import AudioDecoder

decoder = AudioDecoder("speech.wav")          # a path, raw bytes or a file-like object
print(decoder.metadata)                       # AudioStreamMetadata, available before decoding

samples = decoder.get_all_samples()           # an AudioSamples object
waveform = samples.data                       # float tensor, shape (num_channels, num_samples)
sample_rate = samples.sample_rate             # int, for example 44100
print(waveform.shape, sample_rate, samples.duration_seconds)

AudioSamples exposes data, sample_rate, pts_seconds (start time) and duration_seconds. The decoder is lazy: constructing it reads only the metadata, and nothing is decoded until you ask for samples. The audio decoding example also shows a method to decode just a time range (get_samples_played_in_range); check the API reference for its exact signature before using it. Decode only the range you need for long recordings; decoding everything then slicing wastes memory.

Encoding audio

import torch
from torchcodec.encoders import AudioEncoder

sample_rate = 16_000
t = torch.arange(sample_rate) / sample_rate
tone = 0.5 * torch.sin(2 * torch.pi * 440 * t)       # 1 s of a 440 Hz tone, mono, values in [-1, 1]

encoder = AudioEncoder(samples=tone, sample_rate=sample_rate)   # sample_rate is the input rate
as_mp3 = encoder.to_tensor(format="mp3")                        # uint8 tensor of encoded bytes
as_wav = encoder.to_tensor(format="wav", num_channels=2, sample_rate=32000)
encoder.to_file("tone.wav")                                     # see the AudioEncoder docstring for options

The input must be a float tensor in [-1, 1], either 1D (mono) or (num_channels, num_samples). The encoded uint8 tensor can be decoded back with AudioDecoder(encoded).get_all_samples(). The documented encoding options on that page are format, num_channels and sample_rate; the page tells you to read the method docstrings for the full list (the page does not show bit rate options or file-like output, so check the API reference).

Decoding video and sampling clips

from torchcodec.decoders import VideoDecoder
from torchcodec.samplers import clips_at_random_indices

decoder = VideoDecoder("clip.mp4")            # add device="cuda" for NVDEC decoding
print(decoder.metadata)

first = decoder[0]                            # uint8 frame, shape (C, H, W)
some = decoder.get_frames_at(indices=[0, 10, 20])      # a FrameBatch
print(some.data.shape)                        # (N, C, H, W), uint8

clips = clips_at_random_indices(
    decoder,
    num_clips=5,
    num_frames_per_clip=4,
    num_indices_between_frames=3,
)
print(clips.data.shape)                       # (num_clips, num_frames_per_clip, ...), uint8

A VideoDecoder supports indexing and slicing (decoder[0], decoder[10:20]), index-based access (get_frames_at) and time-based access (get_frames_played_at(seconds=...)). Frames are returned as uint8 tensors with presentation timestamps and durations. The torchcodec.samplers module provides ready-made clip samplers for video-model training; clips_at_random_indices, clips_at_regular_timestamps and their relatives return a FrameBatch whose data has a leading clips dimension, pts_seconds and duration_seconds. Use device="cuda" to decode on an NVIDIA GPU with NVDEC; the README tells you to verify the FFmpeg build with ffmpeg -decoders | grep -i nvidia.

Decoding images

TorchCodec also provides decode_image (automatic format detection for JPEG, PNG, WebP, GIF, AVIF and HEIC) and format-specific decode_jpeg, plus JpegEncoder and PngEncoder; JPEG decoding and encoding have CUDA support. These replace the image functions of torchvision.io, which torchvision deprecated in 0.29; see torchvision. The migration guide is at https://meta-pytorch.org/torchcodec/0.16/generated_examples/migration/torchvision_migration.html.

What torchaudio is still good for

Spectrogram features

import torch
import torchaudio.transforms as T

sample_rate = 16_000
waveform = torch.randn(1, sample_rate * 2)             # stand-in for decoded audio: (channels, time)

mel = T.MelSpectrogram(sample_rate=sample_rate, n_fft=400, hop_length=160, n_mels=64)
to_db = T.AmplitudeToDB(top_db=80)

feat = to_db(mel(waveform))                            # (channels, n_mels, frames)
print(feat.shape)

The transforms are nn.Module instances, so they can be placed inside a model, moved to the GPU with .to(device) and applied to batches. Other commonly used transforms include Spectrogram, MFCC, InverseMelScale, GriffinLim, Vol, Fade and Resample. torchaudio.functional has the matching functional forms (resample, spectrogram, lfilter, compute_deltas, …​), see https://docs.pytorch.org/audio/stable/functional.html.

Resampling

Models expect a fixed sample rate (16 kHz for most speech models). Use the Resample transform, and build it once so that its filter kernel is reused:

import torch
import torchaudio.transforms as T

resampler = T.Resample(orig_freq=44_100, new_freq=16_000)
waveform_44k = torch.randn(2, 44_100)
waveform_16k = resampler(waveform_44k)
print(waveform_16k.shape)                              # (2, 16000)

Creating a new Resample for every example in a Dataset.__getitem__ recomputes the kernel each time; create it in __init__ instead.

Augmenting spectrograms

SpecAugment-style masking is available as T.FrequencyMasking and T.TimeMasking, applied to a spectrogram during training only:

import torch
import torchaudio.transforms as T

augment = torch.nn.Sequential(
    T.FrequencyMasking(freq_mask_param=12),
    T.TimeMasking(time_mask_param=30),
)
spec = torch.rand(1, 64, 200)          # (channels, n_mels, frames)
augment.train()
masked = augment(spec)

Pre-trained pipelines

torchaudio.pipelines bundles a model, its weights, its expected sample rate and its label set. The speech recognition tutorial uses wav2vec 2.0 this way:

import torch
import torchaudio

bundle = torchaudio.pipelines.WAV2VEC2_ASR_BASE_960H
model = bundle.get_model().eval()
labels = bundle.get_labels()
print(bundle.sample_rate)                              # 16000: resample inputs to this

waveform = torch.randn(1, bundle.sample_rate * 2)      # stand-in for real 16 kHz audio
with torch.inference_mode():
    emission, _ = model(waveform)                      # (batch, frames, num_labels)
print(emission.shape, len(labels))

The tutorial then decodes the emissions greedily or with the CTC beam search decoder (torchaudio.models.decoder). The documentation lists further tutorials for forced alignment, Tacotron2 text to speech, MVDR beamforming, Hybrid Demucs source separation and Squim quality estimation (see the index page). For large speech models in production most teams now use the Hugging Face ecosystem; see Speech Models.

Putting it together

A typical audio classification input pipeline after the migration:

import torch
import torchaudio.transforms as T
from torch.utils.data import Dataset
from torchcodec.decoders import AudioDecoder

class ClipDataset(Dataset):
    def __init__(self, items, target_sr=16_000, n_mels=64):
        self.items = items                              # list of (path, label)
        self.target_sr = target_sr
        self.mel = T.MelSpectrogram(target_sr, n_fft=400, hop_length=160, n_mels=n_mels)
        self.db = T.AmplitudeToDB()
        self.resamplers = {}                            # cache by original rate

    def __len__(self):
        return len(self.items)

    def __getitem__(self, i):
        path, label = self.items[i]
        s = AudioDecoder(path).get_all_samples()
        wav = s.data.mean(dim=0, keepdim=True)          # mono
        if s.sample_rate != self.target_sr:
            rs = self.resamplers.setdefault(
                s.sample_rate, T.Resample(s.sample_rate, self.target_sr))
            wav = rs(wav)
        return self.db(self.mel(wav)), label

Source: composed from the TorchCodec audio decoding example and the torchaudio transforms documentation.

Variable-length clips need a collate_fn that pads or crops (see Workers, Pinned Memory & Samplers). The cached Resample objects are created lazily inside each worker process.