How to Use the FFmpeg aselect Filter
The aselect filter in FFmpeg is a powerful tool used to
select specific audio frames to output based on a boolean evaluation
expression. This article provides a straightforward guide on how to use
the aselect filter, detailing its basic syntax, key
variables, and practical examples for real-world audio manipulation.
Basic Syntax
The basic syntax for the aselect filter is as
follows:
ffmpeg -i input.mp3 -af "aselect='expression'" output.mp3The filter evaluates the expression for each audio
frame. If the expression evaluates to a non-zero value (true), the frame
is kept. If it evaluates to zero (false), the frame is discarded.
Key Variables and Constants
To build expressions, you can use several variables provided by FFmpeg:
n: The sequential number of the filtered frame, starting from 0.t: The time of the frame in seconds.pts: The presentation timestamp of the frame.tb: The timebase of the input.key: Evaluates to 1 if the frame is a keyframe, 0 otherwise.
Practical Examples
1. Select Audio After a Specific Time
To keep only the audio that occurs after the 10-second mark, use the
gte (greater than or equal to) function with the time
variable t:
ffmpeg -i input.wav -af "aselect='gte(t,10)',asetpts=N/SR/TB" output.wavNote: The asetpts=N/SR/TB filter is added to
recalculate the timestamps of the output file so there is no dead
silence at the beginning.
2. Select a Specific Range of Audio
To extract audio between the 5th and 15th seconds of a file:
ffmpeg -i input.wav -af "aselect='between(t,5,15)',asetpts=N/SR/TB" output.wav3. Select Frames Based on Frame Number
If you want to keep only the first 500 audio frames of a stream:
ffmpeg -i input.wav -af "aselect='lt(n,500)'" output.wav4. Select Every Other Audio Frame
To select alternate audio frames (e.g., every second frame), you can use the modulo operator:
ffmpeg -i input.wav -af "aselect='mod(n,2)'" output.wavImportant: Fixing
Timestamps with asetpts
When you discard frames using aselect, the remaining
frames retain their original presentation timestamps (PTS). This can
lead to playback issues or long stretches of silence.
To fix this, always chain the asetpts filter after
aselect to reset the timestamps:
asetpts=N/SR/TB: Resets timestamps continuously based on the sample rate and frame number.asetpts=PTS-STARTPTS: Shifts timestamps so the first selected frame starts at zero.