Last active
October 2, 2017 09:42
-
-
Save iancoleman/d110d939e460f4b140c15524b00a695e to your computer and use it in GitHub Desktop.
Convert surround sound to stereo for all files in a directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# Convert files with surround sound to use stereo | |
# CAUTION: will overwrite original file! | |
# Some additional bash helpers | |
# convert all videos in directory to smaller size, output in /tmp | |
# for f in `ls | grep mp4`; do ffmpeg -i $f -vf scale=720:-2 -c:a copy /tmp/$f; done | |
# | |
# convert video from surround to stereo, output in /tmp | |
# ffmpeg -i xyz.mkv -c:v copy -ac 2 -af "pan=stereo|FL=0.8*FC+0.40*FL+0.40*BL|FR=0.8*FC+0.40*FR+0.40*BR" /tmp/xyz.mkv | |
import os | |
import subprocess | |
dstRoot = "/tmp" | |
srcRoot = "/path/to/your/media" | |
def main(): | |
for root, dirs, filenames in os.walk(srcRoot): | |
for filename in filenames: | |
filelocation = os.path.join(root, filename) | |
if isVideo(filelocation): | |
surround = isSurround(filelocation) | |
if surround: | |
convertToStereo(filelocation) | |
def log(s): | |
f = open("converted_videos.txt", 'a') | |
f.write(s + "\n") | |
f.close() | |
def isVideo(src): | |
videoExts = ["avi", "mkv", "mp4"] | |
ext = src.split(".")[-1] | |
return ext in videoExts | |
def isSurround(src): | |
cmd = ["ffmpeg", "-i", src] | |
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
lines = p.stderr.decode().split("\n") | |
surround = False | |
for line in lines: | |
if line.find("Audio") > -1 and line.find("5.1") > -1: | |
surround = True | |
break | |
return surround | |
def convertToStereo(src): | |
# Convert | |
filename = os.path.split(src)[-1] | |
log("Converting %s to stereo" % filename) | |
dst = os.path.join(dstRoot, filename) | |
mix = "FL=0.8*FC+0.40*FL+0.40*BL|FR=0.8*FC+0.40*FR+0.40*BR" | |
cmd = [ | |
"ffmpeg", | |
"-i", | |
src, | |
"-c:v", | |
"copy", | |
"-ac", | |
"2", | |
"-af", | |
"pan=stereo|%s" % mix, | |
dst, | |
] | |
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
# Replace with converted file | |
cmd = ["mv", dst, src] | |
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment