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'
      return
      
    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.
    subprocess.call(scmd)
go()
os.system('pause')



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

3 comments:

bugpod said...
This comment has been removed by the author.
stib said...

or:

for i in *.mp4
do ffmpeg -i "$i" -vn -acodec copy "${i/.mp4/_track1.mp4}"
done

(this works for posix shells, I don't know how it would go in a batch script, but the ffmpeg bit would be the same).

ffmpeg is the swiss army knife of video conversion.

ben.fisher said...

@stib -- Cool, didn't know it could be done in ffmpeg. I guess I didn't even need a separate tool.