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.mp3

The 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:

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.wav

Note: 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.wav

3. 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.wav

4. 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.wav

Important: 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: