Rate this Page
★ ★ ★ ★ ★

AudioPacketDecoder#

class torchcodec.decoders.AudioPacketDecoder(*args, **kwargs)[source]#

Decodes the compressed Packets of one audio stream into RawAudioSamples.

This is a low-level API: for straightforward decoding, use AudioDecoder instead.

You should not build one yourself: AudioStream.make_decoder() is what creates it. Audio is always decoded on the CPU.

Feed it one packet at a time, and drain it at the end:

demuxer = Demuxer("audio.mp3", streams="audio")
decoder = demuxer.streams[0].make_decoder()

for packet in demuxer:
    for raw_samples in decoder.decode(packet):
        ...
for raw_samples in decoder.drain():
    ...

It is stateful. A lossy codec carries state from one frame to the next, so it expects the packets of its own stream, in the order the demuxer produced them. After a Demuxer.seek(), reset() is necessary but not sufficient: the first samples that come out are subtly wrong until the codec re-primes, so decode a margin before your target and throw it away.

Examples using AudioPacketDecoder:

Raw frames and raw audio samples

Raw frames and raw audio samples
decode(packet: Packet) → list[RawAudioSamples][source]#

Send one Packet to the codec and return the RawAudioSamples that are ready.

This can return zero, one, or more than one RawAudioSamples. What comes back is not the decoding of the packet you just passed: a codec that is still priming itself will emit what it owes you on a later call.

Parameters:

packet (Packet) – A packet of this decoder’s own stream.

Returns:

The possibly empty list of RawAudioSamples that the codec has ready, in presentation order.

Raises:

RuntimeError – If this decoder has been drained, or if the demuxer seeked without it being reset() afterwards.

drain() → list[RawAudioSamples][source]#

Tell the codec the stream has ended, and return the RawAudioSamples it was still holding.

Skipping this loses the tail of the stream. A drained decoder refuses any further packet; reset() makes it usable again.

Returns:

The possibly empty list of RawAudioSamples that the codec was still holding, in presentation order.

reset() → None#

Drop the codec’s buffered state and start over.

Needed after a Demuxer.seek(), and after drain().