Subscribe via Email

Subscribe via RSS


Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan

Quick ffmpeg tricks (extract audio, convert audio codec of a video)

I use ffmpeg to convert between audio and video formats. Two situations I use it for are: (1) when I have a video whose audio codec is of a format my media players can’t handle (I use WD TV Live and it has trouble with certain formats), or (2) when I want to extract the audio only from a video. 

For converting only the audio here’s the command I use:

The syntax is pretty obvious. The input file is taken, the video codec is copied as-is to the new file, the audio codec is re-encoded to mp3. I could have used -acodec mp3 too. In the past there used to be an in-built mp3 encoder as well as the mp3 encoder provided by the LAME project (ffmpeg must be built with LAME encoder via the --enable-libmp3lame switch for this to work) so you could choose between either via the two switches, but now there’s no in-built encoder so both --acodec mp3 and --acodec libmp3lame do the same. 

To confirm what switches ffmpeg was built with simply run the command. For example, on my machine:

Notice it was built with --enable-libmp3lame

When it comes to extracting just the audio from a video there’s two ways to do it: 1) you can simply extract the audio in the codec as it is, or 2) you can extract & convert to the codec you want. The latter has the disadvantage that if the original video is in a lossy audio codec, converting will result in some degradation of quality. 

To check what audio codec the file is in, do the following: 

Notice it identifies the audio stream as AAC in this case. If I am happy with extracting that as it is I can do the following:

The -vn switch tells ffmpeg to ignore the video. The -acodec copy switch tells it to copy the audio codec as it is. Since this is an AAC file, I assign an extension of .aac to the output file. 

However, if I didn’t want the audio stream as AAC, I would have done the following:

Here I am converting the audio to mp3. Once again I ignore the video via -vn. I specify the audio codec via -acodec libmp3lame. The rest of the switches are as follows:

  • -ac 2 => two channels (stereo) (note this is same as the input, so is an optional switch)
  • -ar 44100 => sammple rate 44100 Hz (CD quality) (note this is same as the input, so is an optional switch)
  • -ab 320k => bit-rate of 320 kb/s (if I don’t specify this the bit-rate will be 128 kb/s for mp3)

Essentially, instead of just copying the audio codec you convert it. Otherwise the idea is the same. Apart from libmp3lame (or mp3) I could have also used the following audio codecs: vorbis (for ogg), aac, flac, and wma

Before concluding, here’s a link to ffmpeg’s documentation (for all the command-line switches etc). Also, this is a good page on audio/ video containers and ffmpeg. The latter is a very thorough and informative page, I am sure I’ll be referring to it in the future.