How to Use FFmpeg asetpts Filter to Adjust Audio Timestamps
Adjusting audio timestamps in FFmpeg is crucial for fixing
audio-video synchronization issues, altering playback speed, and
resetting timelines for seamless concatenation. This article explains
how to use the asetpts (audio set presentation timestamp)
filter, covering its basic syntax and demonstrating how to apply
practical expressions to shift, scale, and reset audio timestamps.
Understanding the asetpts Filter
The asetpts filter works by modifying the Presentation
Timestamp (PTS) of each audio frame. The PTS determines exactly when a
specific frame of audio should be played relative to the start of the
stream.
The basic syntax for the filter is:
-af "asetpts=EXPRESSION"FFmpeg provides several built-in variables for the expression,
including: * PTS: The original
presentation timestamp of the current frame. *
STARTPTS: The presentation timestamp of
the first frame. * TB: The time base of
the audio stream. * SAMPLE_RATE (or
SR): The audio sample rate.
Common Use Cases
1. Resetting Audio Timestamps to Zero
When cutting or merging audio files, the resulting stream may inherit
non-zero starting timestamps, causing playback issues in some media
players. You can reset the timeline so the audio starts precisely at
zero using PTS-STARTPTS:
ffmpeg -i input.mp3 -af "asetpts=PTS-STARTPTS" output.mp32. Shifting Audio to Fix Desynchronization
If your audio is out of sync with your video, you can shift the audio timeline forward or backward.
Delay audio by 1.5 seconds:
ffmpeg -i input.mp4 -af "asetpts=PTS+1.5/TB" output.mp4Advance audio by 1.5 seconds (make it play earlier):
ffmpeg -i input.mp4 -af "asetpts=PTS-1.5/TB" output.mp4
(Note: TB represents the time base, which translates
the real-world seconds into the stream’s internal timestamp
units.)
3. Changing Playback Speed
While the atempo filter is typically used to change
audio speed without changing pitch, the asetpts filter can
be used to adjust the container-level playback timestamps to match video
speed changes (like those done with the video setpts
filter).
Double the playback speed (half the presentation time):
ffmpeg -i input.wav -af "asetpts=0.5*PTS" output.wavHalve the playback speed (double the presentation time):
ffmpeg -i input.wav -af "asetpts=2.0*PTS" output.wav
Combining Video and Audio Timestamp Adjustments
When adjusting timestamps for a video file, you must apply
setpts to the video stream and asetpts to the
audio stream simultaneously to keep them in sync.
For example, to fast-forward a video to 2x speed while keeping the audio synchronized:
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