Extracting and re-combining audio from a video

First of all, make sure you install the latest version of FFmpeg from their download page. For Windows, Linux and OS X there are static builds available. On OS X you can also use Homebrew (with brew install ffmpeg).

Extract audio from a video

To extract the audio stream from a file, we export to PCM stereo audio in a WAV container, since it's lossless and won't be re-encoded:

ffmpeg -i input-file.avi audio.wav

Of course, you could use a number of other codecs, such as FLAC or ALAC. PCM content in WAV (or AIFF on Apple) would probably be best for editing though.

Now, apply any effects to your audio stream as necessary.

Recombine audio and video

To recombine an audio stream and a video file, run:

ffmpeg -i input-file.avi -i audio.wav -c copy -map 0:0 -map 1:0 output.avi

Remarks

It is important that the video and audio files are in the correct order (-i video, -i audio) for the stream mapping. Might not work otherwise.

The -map 0:0 -map 1:0 option will map the audio from the second input file (the 1 in 1:0) to the AVI instead of using the original audio. This is the most important parameter here.

You could theoretically change the -c copy to just copy the video bitstream (-c:v copy) and use any other compressed audio codec, because copy will try to use the uncompressed PCM stereo audio. Similarly, you could of course just save the edited audio file to MP3 and use that instead, but keep copy.

To encode the PCM stereo WAV file to MP3, do something like this:

ffmpeg -i input-file.avi -i audio.wav -c:v copy -c:a libmp3lame -map 0:0 -map 1:0 output.avi

If your audio file is shorter than the video file, you might want to loop it. Supply the -loop 1 option to do this.