How to Use the FFmpeg asetpts Filter

This article provides a straightforward guide on how to use the asetpts (Audio Set Presentation TimeStamp) filter in FFmpeg. You will learn what the filter does, its basic syntax, and practical examples for adjusting audio speed, syncing audio with video, and resetting timestamps for seamless playback.

What is the asetpts Filter?

The asetpts filter in FFmpeg is used to modify the Presentation Timestamps (PTS) of audio packets. Timestamps decide exactly when a specific frame of audio should be played back. By manipulating these timestamps, you can speed up or slow down audio playback, fix sync issues between audio and video, or reset timestamps to start from zero.

Basic Syntax

The basic syntax for the asetpts filter is:

-af "asetpts=EXPRESSION"

Inside the expression, you can use several built-in FFmpeg variables. The most common ones are: * PTS: The original presentation timestamp of the current input frame. * STARTPTS: The presentation timestamp of the very first audio frame. * SAMPLE_RATE (or SR): The audio sample rate. * TB: The time base of the audio stream.


Practical Examples

1. Resetting Audio Timestamps to Start at Zero

When concatenating audio files or editing streams, the audio may contain offset timestamps that cause playback errors. You can reset the timestamps to start exactly at zero using the following command:

ffmpeg -i input.wav -af "asetpts=PTS-STARTPTS" output.wav

This subtracts the initial start timestamp from every subsequent timestamp, forcing the stream to start at 0.

2. Doubling the Speed of Audio (2x)

To make the audio play twice as fast, you need to halve the time intervals between the audio frames. You do this by multiplying the PTS by 0.5:

ffmpeg -i input.mp3 -af "asetpts=0.5*PTS" output.mp3

Note: Using asetpts alone to speed up audio will change the presentation timing but can result in dropped audio samples or stuttering. To speed up audio cleanly with pitch correction, it is recommended to pair it with the atempo filter.

3. Halving the Speed of Audio (0.5x)

To slow the audio down to half-speed, you need to double the time intervals between the frames. You do this by multiplying the PTS by 2.0:

ffmpeg -i input.mp3 -af "asetpts=2.0*PTS" output.mp3

4. Syncing Audio Speed with Video Speed

The asetpts filter is most commonly used in conjunction with the video equivalent, setpts, to speed up or slow down an entire video file while keeping the audio and video in sync.

To speed up both video and audio by 2x:

ffmpeg -i input.mp4 -filter_complex "[0:v]setpts=0.5*PTS[v];[0:a]asetpts=0.5*PTS[a]" -map "[v]" -map "[a]" output.mp4

To slow down both video and audio to 0.5x speed:

ffmpeg -i input.mp4 -filter_complex "[0:v]setpts=2.0*PTS[v];[0:a]asetpts=2.0*PTS[a]" -map "[v]" -map "[a]" output.mp4