0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ffmpegで動画のサイズと拡張子を一括変換

Last updated at Posted at 2025-01-02

概要

pythonのos.system関数から、ffmpegを呼び出して動画のサイズや拡張子を一括で変更するスクリプトです。サイズや拡張子の指定がなければ、オリジナルの情報を引き継ぎます。

注:2021年に書いた記事です。当時は自分用として限定公開にしていましたが、積極的に隠すほどでもないと考え直して公開します。

環境

% sw_vers
ProductName:    macOS
ProductVersion: 11.4
BuildVersion:   20F71
% python -V
Python 3.8.6

コード

import os
import random, string

INPUT_DIR = os.path.join("input") #path to input movie directory
OUTPUT_DIR = os.path.join("output") #path to output movie directory

def randomname(n):
   randlst = [random.choice(string.ascii_letters + string.digits) for i in range(n)]
   return ''.join(randlst)
   
def convert(input=None, output=None, width=None, ext=None, skip=True):
  if input is None: input=INPUT_DIR
  if output is None: output=OUTPUT_DIR
  if width is None: width = OUTPUT_WIDTH

  os.makedirs(output, exist_ok=True)

  files = os.listdir(input)
  files = [f for f in files if f.split(".")[-1] in ["mp4","MP4","m4v","MOV","mov"]]
  input_files = [os.path.join(input, f) for f in files]
  if ext:
    output_files = [os.path.join(output, "{}.{}".format(".".join(f.split(".")[:-1]), ext)) for f in files]
  else:
    output_files = [os.path.join(output, f) for f in files]

  for ipt, opt in zip(input_files, output_files):
    if skip and os.path.exists(opt):
      print("{} is skipped".format(ipt))
      continue
    tmpopt = opt
    if os.path.exists(opt):
      tmpopt = "{}{}.{}".format(".".join(opt.split(".")[:-1]), randomname(12), opt.split(".")[-1])
      
    if width:
      cmd = f"ffmpeg -i {ipt} -vf scale={width}:-1 {tmpopt}"
    else:
      cmd = f"ffmpeg -i {ipt} {tmpopt}"
    os.system(cmd)
    if not skip:
      cmd = "mv {} {}".format(tmpopt, opt)
      os.system(cmd)

if __name__=="__main__":
  convert(width=854, ext="mp4")

参考

Pythonを使ってランダムな文字列を生成

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?