一个完整的脚本,用于计算文件夹下所有 m4a 音频文件的总长度,并输出为小时、分钟和秒的格式:
import os from mutagen.mp4 import MP4 def calculate_total_duration(folder_path): m4a_files = [f for f in os.listdir(folder_path) if f.endswith('.m4a')] total_length = 0 for file in m4a_files: file_path = os.path.join(folder_path, file) audio = MP4(file_path) length = audio.info.length total_length += length return total_length def convert_seconds_to_time_format(total_seconds): hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 seconds = total_seconds % 60 return int(hours), int(minutes), seconds if __name__ == "__main__": folder_path = input("请输入文件夹路径: ") total_length = calculate_total_duration(folder_path) hours, minutes, seconds = convert_seconds_to_time_format(total_length) print(f'音频文件的总长度为:{hours}小时,{minutes}分钟,{seconds:.2f}秒')
只需将上述脚本保存为 .py
文件(例如 calculate_audio_length.py
),然后在命令行或终端中运行它。当程序提示你输入文件夹路径时,输入含有 m4a 文件的文件夹的路径,然后程序会为你输出总长度。