Skip to content

Instantly share code, notes, and snippets.

@RyougiKukoc
Created May 3, 2023 06:40
Show Gist options
  • Save RyougiKukoc/43c0955d2c583972bd0a8898b2991678 to your computer and use it in GitHub Desktop.
Save RyougiKukoc/43c0955d2c583972bd0a8898b2991678 to your computer and use it in GitHub Desktop.
mkv / m2ts audio extractor
import os
import argparse
import sys
import time
import msvcrt
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-d', type=str, default='./',
help='-d: specify the path to your workspace')
parser.add_argument('-t', '--track', type=int, default=2,
help='-t, --track: specify the default track to extract')
parser.add_argument('-f', '--force', action='store_true',
help='-f, --force: force extract without showing info for every file')
args = parser.parse_args()
acext = ['.mkv', '.m2ts']
DEFAULT_TIMEOUT = 5.0
INTERVAL = 0.05
SP = ' '
CR = '\r'
LF = '\n'
CRLF = CR + LF
class TimeoutOccurred(Exception):
pass
def echo(string):
sys.stdout.write(string)
sys.stdout.flush()
def win_inputimeout(prompt='', timeout=DEFAULT_TIMEOUT):
echo(prompt)
begin = time.monotonic()
end = begin + timeout
line = ''
while time.monotonic() < end:
if msvcrt.kbhit():
c = msvcrt.getwche()
if c in (CR, LF):
echo(CRLF)
return line
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
line = line[:-1]
cover = SP * len(prompt + line + SP)
echo(''.join([CR, cover, CR, prompt, line]))
else:
line += c
time.sleep(INTERVAL)
echo(CRLF)
raise TimeoutOccurred
def extract_audio(ws):
for fn in os.listdir(ws):
fp = os.path.join(ws, fn)
if os.path.isdir(fp):
extract_audio(fp)
continue
if not os.path.splitext(fp)[-1] in acext:
continue
if not args.force:
print('-' * 80)
print('Working on ' + fp)
print('-' * 80)
os.system(f'eac3to "{fp}"')
try:
input_track = win_inputimeout('Specify track id to extract, press p to pass this file: ', 5)
except:
print(f"Use default track {args.track}")
input_track = args.track
if input_track == 'p':
print('\n')
continue
input_track = int(input_track)
flac_fp = fp + '.flac'
os.system(f'eac3to "{fp}" {input_track}: "{flac_fp}"')
else:
flac_fp = fp + '.flac'
os.system(f'eac3to "{fp}" {args.track}: "{flac_fp}"')
extract_audio(os.path.abspath(args.d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment