代码中m4a可以换成mp3,图片和音频放同一目录,图片名image.jpg,多线程max_workers可以根据CPU核心数量修改。
import os
import subprocess
import sys
import concurrent.futures
import ffmpeg
def get_media_duration(media_path):
probe = ffmpeg.probe(media_path)
format = probe['format']
duration = format['duration']
print('duration: {}'.format(duration))
return duration
def convert_m4a_to_mp4(input_file_path,imput_image_path, output_file_path):
#ffmpeg -r 10 -f image2 -loop 1 -i image.jpg -i 01.mp3 -s 1920x1080 -pix_fmt yuvj420p -t 281 -vcodec libx264 output.mp4
print(input_file_path)
duration = get_media_duration(input_file_path)
cmd = f"ffmpeg -r 10 -f image2 -loop 1 -i \"{imput_image_path}\" -i \"{input_file_path}\" -s 640*480 -pix_fmt yuvj420p -t {duration} -vcodec libx264 \"{output_file_path}\""
os.system(cmd)
def convert_files(input_folder, output_folder):
检查输出文件夹是否存在,如果不存在则创建
if not os.path.exists(output_folder):
os.makedirs(output_folder)
创建 ThreadPoolExecutor,并限制最大线程数为 16
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
遍历输入文件夹中的所有 WAV 文件
for root, dirs, files in os.walk(input_folder):
for filename in files:
if filename.endswith(".m4a"):
input_image_path = os.path.join(root, "image.jpg")
input_file_path = os.path.join(root, filename)
output_file_path = os.path.join(output_folder, os.path.splitext(filename)[0] + ".mp4")
提交任务给线程池
executor.submit(convert_m4a_to_mp4, input_file_path,input_image_path, output_file_path)
等待所有任务完成后退出
executor.shutdown()
if name == "main":
从命令行获取输入和输出文件夹的路径
if len(sys.argv) != 2:
print("Usage: python script.py input_folder")
sys.exit(1)
input_folder = sys.argv[1]
output_folder = sys.argv[1]
convert_files(input_folder, output_folder)