DEV Community

GoToolsOnline
GoToolsOnline

Posted on

Extracting audio from video with ffmpeg without re-encoding

The most common way people pull audio out of a video is ffmpeg -i in.mp4 out.mp3. It works, but it decodes the audio and encodes it again, so you lose a little quality and wait longer than you need to. Usually you can just copy the stream.

1. Check what codec the audio already is

ffprobe -v error -select_streams a -show_entries stream=index,codec_name,channels -of csv=p=0 in.mp4
Enter fullscreen mode Exit fullscreen mode

Phone and camera MP4s are almost always aac. WebM is usually opus or vorbis. MKV can be anything.

2. Copy it into a container that fits the codec

# AAC -> .m4a, bit-for-bit the same sound
ffmpeg -i in.mp4 -vn -c:a copy out.m4a

# Opus from a WebM -> .opus
ffmpeg -i in.webm -vn -c:a copy out.opus
Enter fullscreen mode Exit fullscreen mode

-vn drops the video and -c:a copy keeps the audio packets as they are. If the container can't hold that codec (for example AAC into a .wav), ffmpeg will refuse, and that's your cue to pick a different extension, not to re-encode.

3. Pick the right track

Files with several audio tracks (languages, or mic and system sound in screen recordings) default to one track only. Choose explicitly:

ffmpeg -i in.mkv -map 0:a:1 -c:a copy second_track.mka
Enter fullscreen mode Exit fullscreen mode

0:a:1 is the second audio stream of the first input (counting starts at 0).

4. Only re-encode when you actually need a format

ffmpeg -i in.mp4 -vn -c:a libmp3lame -b:a 192k out.mp3   # MP3 for old players
ffmpeg -i in.mp4 -vn -c:a pcm_s16le out.wav               # WAV for editing
Enter fullscreen mode Exit fullscreen mode

192 kbps is a sensible default for music, 128 kbps for speech. WAV and FLAC keep exactly what was in the video, but they can't add back detail the video's audio never had.

5. Trimming at the same time

ffmpeg -i in.mp4 -ss 75 -to 135 -vn -c:a copy clip.m4a
Enter fullscreen mode Exit fullscreen mode

With -c:a copy the cut lands on an audio packet boundary, which for AAC is a few tens of milliseconds, close enough for almost everything. If you need it sample-exact, re-encode instead.


Disclosure: I run GoToolsOnline, which has a free browser version of this (original audio or MP3/M4A/WAV/FLAC, track picker, start/end time): Extract Audio from Video

Top comments (0)