A fade-in is easy in ffmpeg. A fade-out is not, because the filter needs to know when to start. You must give it the start time, and that depends on how long the file is.

Fade in

ffmpeg -i song.mp3 -af "afade=t=in:d=3" song_in.mp3 

t=in is the type and d=3 is the length in seconds. The fade starts at the beginning by default. Nothing else is needed.

Fade out needs a start time

ffmpeg -i song.mp3 -af "afade=t=out:st=177:d=3" song_out.mp3 

st=177 means start the fade at second 177. For a 180 second song and a 3 second fade, that ends exactly at the end. If you leave out st, the fade starts at 0 and the whole song fades out.

So you need the duration first. Get it with ffprobe:

ffprobe -v error -show_entries format=duration -of csv=p=0 song.mp3 

Both in one pass

Chain the filters with a comma:

ffmpeg -i song.mp3 -af "afade=t=in:d=2,afade=t=out:st=176:d=4" song_faded.mp3 

A small Python helper

import subprocess def duration(path): out = subprocess.run( ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], capture_output=True, text=True, check=True) return float(out.stdout.strip()) def fade_filter(path, fade_in=0, fade_out=0): filters = [] if fade_in > 0: filters.append(f"afade=t=in:d={fade_in}") if fade_out > 0: start = max(0, duration(path) - fade_out) filters.append(f"afade=t=out:st={start}:d={fade_out}") return ",".join(filters) or "anull" 

Two details. max(0, ...) stops a negative start when the fade is longer than the clip. And anull is a filter that does nothing, so the command still works when both fades are zero.

Edge cases

  • A fade longer than the file just fades the whole clip. Cap it at the duration.
  • A fade-out on a trimmed file needs the duration of the trimmed file, not the original. Measure after trimming.
  • Filters decode the audio, so the file is re-encoded. You cannot use -c:a copy. Keep the original.

Fade curves

afade has a curve option. The default is a straight line. Try curve=qsin for a smoother ending, which many people find sounds more natural for music.

Use it in the browser

The audio fade tool on MPY3JUICES takes a fade-in and a fade-out length in seconds, plus the clip length. The server subtracts the fade-out from the clip length to get the start time, as above.