-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmp4tomp3.py
65 lines (53 loc) · 2.59 KB
/
mp4tomp3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# MP4 TO MP3 CONVERSION SCRIPT
# script to convert mp4 video files to mp3 audio
# useful for turning video from sites such as www.ted.com into audio files useable
# on any old mp3 player.
#
# usage: python mp4tomp3.py [input directory [output directory]]
# input directory (optional) - set directory containing mp4 files to convert (defaults to current folder)
# output directory (optional) - set directory to export mp3 files to (defaults to input)
#
# NOTE: you will need python 2, mplayer and lame for this script to work
# sudo apt-get install lame
# sudo apt-get install mplayer
# sudo apt-get install python2.7
from subprocess import call # for calling mplayer and lame
from sys import argv # allows user to specify input and output directories
import os # help with file handling
def check_file_exists(directory, filename, extension):
path = directory + "/" + filename + extension
return os.path.isfile(path)
def m4tm3(indir, outdir):
try:
# check specified folders exist
if not os.path.exists(indir):
exit("Error: Input directory \'" + indir + "\' does not exist. (try prepending './')")
if not os.path.exists(outdir):
exit("Error: Output directory \'" + outdir + "\' does not exist.")
if not os.access(outdir, os.W_OK):
exit("Error: Output directory \'" + outdir + "\' is not writeable.")
print("[%s/*.mp4] --> [%s/*.mp3]" % (indir, outdir))
files = [] # files for exporting
# get a list of all convertible files in the input directory
filelist = [f for f in os.listdir(indir) if f.endswith(".mp4")]
for path in filelist:
basename = os.path.basename(path)
filename = os.path.splitext(basename)[0]
files.append(filename)
# remove files that have already been outputted from the list
files[:] = [f for f in files if not check_file_exists(outdir, f, ".mp3")]
except OSError as e:
exit(e)
# convert all unconverted files
for filename in files:
print("-- converting %s.mp4 to %s.mp3 --" % (indir + "/" + filename, outdir + "/" + filename))
call(["mplayer", "-novideo", "-nocorrect-pts", "-ao", "pcm:waveheader", indir + "/" + filename + ".mp4"])
call(["lame", "-h", "-b", "192", "audiodump.wav", outdir + "/" + filename + ".mp3"])
os.remove("audiodump.wav")
# set the default directories and try to get input directories
args = [".", "."]
for i in range(1, min(len(argv), 3)):
args[i - 1] = argv[i]
# if only input directory is set, make the output directory the same
if len(argv) == 2:
args[1] = args[0]