Script Python tạo video sử dụng FFMPEG

Bài viết này sẽ hướng dẫn các bạn tạo script python sử dụng FFMPEG tạo hàng loạt video từ file mp3 và file ảnh làm background.

Nội dung Script

Script python này sẽ tìm kiếm file mp3 trong thư mục được chỉ định, tạo video và xóa file mp3 sau khi hoàn thành.

Xem thêm: Cài đặt và sử dụng ffmpeg

Nội dung:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import glob,os
import os.path
import datetime
import logging
import sys
import time
import logging, logging.handlers

def modification_date(filename):
    t = os.path.getmtime(filename)
    return datetime.datetime.fromtimestamp(t)

MP3_FOLDER_NAME = "/mp3"

def findMP3folder(path="/tmp/"):
  extension = "*.mp3"
  rs = []
  if(not os.path.exists(path)):
    return rs

  for fol in glob.glob(path+"/*"):
    if(os.path.isdir(fol) and os.path.isdir(fol+MP3_FOLDER_NAME) and os.path.exists(fol+MP3_FOLDER_NAME)):
      rs.append(fol+MP3_FOLDER_NAME+"/"+extension)
  return rs

def setup_custom_logger(name):
    formatter = \
        logging.Formatter(fmt='%(asctime)s %(levelname)-2s %(message)s'
                          , datefmt='%Y-%m-%d %H:%M:%S')
    handler = logging.handlers.RotatingFileHandler("/tmp/create_video/make_videos.log", maxBytes=9000000, backupCount=15)
    handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler()
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger

logger = setup_custom_logger('myapp')

IMG = "/tmp/create_video/image/test.png"
OUT = "/tmp/create_video/video/"

def make_video(FOLDER):
    for mp3_file in glob.glob(FOLDER):
      try:
        diff_sec = (datetime.datetime.now() - modification_date(mp3_file)).total_seconds()
        if(diff_sec<5): 
          continue 
        logger.info("Make video from: %s",mp3_file) 
        cmd = "ffmpeg -loop 1 -i "+IMG+" -i "+mp3_file+" -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 "+OUT+(os.path.splitext(os.path.basename(mp3_file))[0])+".mp4 >/dev/null 2>&1"
        logger.info(cmd)
        os.system(cmd)
        logger.info("Finish. Delete mp3 file: %s",mp3_file)
        os.remove(mp3_file)
      except Exception as errtxt:
        logger.error("Can not make videos file - Error: %s"%errtxt)
        break

if __name__ == '__main__':

  logger.info("Make Videos Script")

  MP3_FOLDERs = findMP3folder()

  if(len(MP3_FOLDERs)<1):
    logger.error("Cannot find any mp3 folder. Exit Script")
    sys.exit()
  else :
    logger.info("MP3_FOLDER LIST: ")
    for MP3_FOLDER in MP3_FOLDERs :
      logger.info(MP3_FOLDER)
  while True:
    for fol in MP3_FOLDERs:
      make_video(fol)
      time.sleep(5)

Áp dụng

Ví dụ mình sẽ tạo các thư mục như sau

  • /tmp/create_video/mp3 #Thư mục để file mp3
  • /tmp/create_video/image #Thư mục để file ảnh
  • /tmp/create_video/video #Thư mục để file video

Liệt kê file trong các thư mục:

Thư mục để file mp3

[root@ITFROMZERO create_video]# ls -l mp3/
total 73760
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_10.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:55 test_1.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_2.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_3.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_4.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_5.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_6.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_7.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_8.mp3
-rw-r--r-- 1 root root 7550469 Jan  7 15:56 test_9.mp3

Thư mục để file ảnh

[root@ITFROMZERO create_video]# ls -l image/
total 560
-rw-r--r-- 1 root root 569850 Jan  4 12:51 test.png

Thư mục để file video

[root@ITFROMZERO create_video]# ls -l video/
total 0

Chạy script

[root@ITFROMZERO create_video]# python make_videos.py
2019-01-07 15:59:47 INFO Make Videos Script
2019-01-07 15:59:47 INFO MP3_FOLDER LIST:
2019-01-07 15:59:47 INFO /tmp/create_video/mp3/*.mp3
2019-01-07 15:59:47 INFO Make video from: /tmp/create_video/mp3/test_1.mp3
2019-01-07 15:59:47 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_1.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_1.mp4 >/dev/null 2>&1
2019-01-07 15:59:51 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_1.mp3
2019-01-07 15:59:51 INFO Make video from: /tmp/create_video/mp3/test_2.mp3
2019-01-07 15:59:51 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_2.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_2.mp4 >/dev/null 2>&1
2019-01-07 15:59:55 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_2.mp3
2019-01-07 15:59:55 INFO Make video from: /tmp/create_video/mp3/test_3.mp3
2019-01-07 15:59:55 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_3.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_3.mp4 >/dev/null 2>&1
2019-01-07 15:59:59 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_3.mp3
2019-01-07 15:59:59 INFO Make video from: /tmp/create_video/mp3/test_4.mp3
2019-01-07 15:59:59 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_4.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_4.mp4 >/dev/null 2>&1
2019-01-07 16:00:03 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_4.mp3
2019-01-07 16:00:03 INFO Make video from: /tmp/create_video/mp3/test_5.mp3
2019-01-07 16:00:03 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_5.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_5.mp4 >/dev/null 2>&1
2019-01-07 16:00:06 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_5.mp3
2019-01-07 16:00:06 INFO Make video from: /tmp/create_video/mp3/test_6.mp3
2019-01-07 16:00:06 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_6.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_6.mp4 >/dev/null 2>&1
2019-01-07 16:00:10 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_6.mp3
2019-01-07 16:00:10 INFO Make video from: /tmp/create_video/mp3/test_7.mp3
2019-01-07 16:00:10 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_7.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_7.mp4 >/dev/null 2>&1
2019-01-07 16:00:14 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_7.mp3
2019-01-07 16:00:14 INFO Make video from: /tmp/create_video/mp3/test_8.mp3
2019-01-07 16:00:14 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_8.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_8.mp4 >/dev/null 2>&1
2019-01-07 16:00:18 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_8.mp3
2019-01-07 16:00:18 INFO Make video from: /tmp/create_video/mp3/test_9.mp3
2019-01-07 16:00:18 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_9.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_9.mp4 >/dev/null 2>&1
2019-01-07 16:00:22 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_9.mp3
2019-01-07 16:00:22 INFO Make video from: /tmp/create_video/mp3/test_10.mp3
2019-01-07 16:00:22 INFO ffmpeg -loop 1 -i /tmp/create_video/image/test.png -i /tmp/create_video/mp3/test_10.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -t 5 /tmp/create_video/video/test_10.mp4 >/dev/null 2>&1
2019-01-07 16:00:26 INFO Finish. Delete mp3 file: /tmp/create_video/mp3/test_10.mp3

Kết quả trong thư mục để video

[root@ITFROMZERO create_video]# ls -l video/
total 2400
-rw-r--r-- 1 root root 243483 Jan  7 16:00 test_10.mp4
-rw-r--r-- 1 root root 243483 Jan  7 15:59 test_1.mp4
-rw-r--r-- 1 root root 243483 Jan  7 15:59 test_2.mp4
-rw-r--r-- 1 root root 243483 Jan  7 15:59 test_3.mp4
-rw-r--r-- 1 root root 243483 Jan  7 16:00 test_4.mp4
-rw-r--r-- 1 root root 243483 Jan  7 16:00 test_5.mp4
-rw-r--r-- 1 root root 243483 Jan  7 16:00 test_6.mp4
-rw-r--r-- 1 root root 243483 Jan  7 16:00 test_7.mp4
-rw-r--r-- 1 root root 243483 Jan  7 16:00 test_8.mp4
-rw-r--r-- 1 root root 243483 Jan  7 16:00 test_9.mp4

Sau khi tạo file thành công, các file mp3 đã bị xóa

[root@ITFROMZERO create_video]# ls -l mp3/
total 0

Như vậy mình đã hướng dẫn các bạn tạo video hàng hoạt bằng script python kết hợp ffmpeg. Chúc các bạn thành công.