Share Code FFMPEG lấy tên file đưa vào làm text trên video

zanmezu

New member
FFMPEG
Lấy tên file đưa vào làm text trên video
Tự động ngắt khi gặp "#".
Yêu cầu : Python, ffmpeg, tạo sẵn thư mục mặc định, "input", "output".
Code:
Python:
import subprocess
import os

def wrap_text(text, max_chars_per_line):
    words = text.split()
    wrapped_text = ""
    line = ""
    for word in words:
        if len(line) + len(word) + 1 <= max_chars_per_line:
            line += word + " "
        else:
            wrapped_text += line.rstrip() + "\n"
            line = word + " "
    wrapped_text += line.rstrip()  # Add the last line
    return wrapped_text

# Define the input and output directories
input_dir = 'input'
output_dir = 'output'

# Create the output directory if it doesn't exist
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# Specify the path to the font file
font_path = 'C:\Windows\Fonts\.VnAristote Medium'  # Update this path to the font you have and want to use

# Loop through all the .mp4 files in the input directory
for input_file in os.listdir(input_dir):
    if input_file.endswith(".mp4"):
        # Construct the full file paths
        input_file_path = os.path.join(input_dir, input_file)
        output_file_path = os.path.join(output_dir, os.path.splitext(input_file)[0] + '_text.mp4')

        # Extract the file name without the extension
        file_name_without_extension = os.path.splitext(input_file)[0]

        # Get the text before the "#" character
        text_to_display = file_name_without_extension.split('#')[0]

        # Wrap the text to fit the video frame without breaking words
        max_chars_per_line = 30  # Adjust as needed for your video size
        text_to_display = wrap_text(text_to_display, max_chars_per_line)

        # Construct the FFmpeg command
        command = [
            'ffmpeg',
            '-i', input_file_path,
            '-vf', f"drawtext=text='{text_to_display}':fontfile='{font_path}':fontcolor=white:fontsize=24:x=(w-text_w)/2:y=(h-text_h)/2",
            '-codec:a', 'copy',
            output_file_path
        ]

        # Execute the command
        subprocess.run(command)

print("Batch processing complete.")
 
Back
Top