Sunday, December 16, 2012

Extracting audio from a .mp4 video

I've been using my Android phone to record snippets of audio, usually some fragment of music. In the past, I would extract the audio by recording playback, using a tool like Total Recorder. However, a better way to isolate the audio is to extract the audio data (demux) from the video, so that I won't lose any quality to re-encoding. The following works well:

Download MP4Box, which comes as part of GPAC. The only part of GPAC needed is MP4Box.

I wrote a little python script. If I drag and drop any number of .mp4 videos to it, _track1.mp4 audio files will be written out. (Adjust as necessary to point to MP4Box or change which track id to export).

import os,sys,subprocess

def go():
  for arg in sys.argv[1:]:
    print arg
    s = 'full/path/to/MP4Box.exe'
    if not arg.endswith('.mp4'):
      print 'must end with .mp4'
    outfile = arg.replace('.mp4','_track1.mp4')
    assert not os.path.exists(outfile)
    scmd = '"%s" -single 1 "%s"'%(s,arg)
    # -single 1 means to extract track id 1 in an mp4 container.

If you want a full GUI (at the expense of bulk operations), Yamb looks like a candidate. It depends on MP4Box.