Skip to content

Instantly share code, notes, and snippets.

@HAKSOAT
Created January 26, 2023 19:01
Show Gist options
  • Select an option

  • Save HAKSOAT/62012a66b67e9219085b49e1f747b858 to your computer and use it in GitHub Desktop.

Select an option

Save HAKSOAT/62012a66b67e9219085b49e1f747b858 to your computer and use it in GitHub Desktop.
import os
from asyncio import create_subprocess_shell, subprocess as aio_subprocess
from datetime import timedelta
SAVE_FORMAT = "{title}-{start}-{duration}.{extension}"
async def aio_exec(command):
result = await create_subprocess_shell(command, stdout=aio_subprocess.PIPE, stderr=aio_subprocess.PIPE)
stdout, stderr = await result.communicate()
if stderr:
return stderr, False
else:
return stdout, True
async def clip(filename, start=0, stop=None, overwrite=False):
if start == 0 and stop is None:
raise ValueError("start and stop MUST NOT be 0 and None at the same time as that means the entire file.")
duration = stop - start if stop else None
name, ext = os.path.splitext(filename)
ext = ext.strip(".")
clip_filepath = SAVE_FORMAT.format(title=name, start=start, duration=duration, extension=ext)
overwrite = "-y" if overwrite else "-n"
if duration:
command = f"ffmpeg {overwrite} -ss {timedelta(seconds=start)} -i \'{filename}\' " \
f"-t {timedelta(seconds=duration)} -c copy '{clip_filepath}' -loglevel error"
else:
command = f"ffmpeg {overwrite} -ss {timedelta(seconds=start)} -i \'{filename}\' " \
f"-c copy '{clip_filepath}' -loglevel error"
output, status = await aio_exec(command)
if not status:
raise Exception(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment