2023/09/10

使用Python 取得Windows 某個資料夾中 mp3音源長度

結果:
[
    26.808,
    31.536,
    13.8,
    9.096,
    8.088,
    9.48,
    3.672,
    3.408,
    7.224,
    5.112,
    9.288,
    5.352,
    3.072,
    3.816,
    2.592,
    3.624,
    2.976,
    5.016,
    2.448,
    2.832,
    4.824,
    3.912,
    2.928,
    2.472,
    2.328,
    7.248,
    6.672,
    3.576,
    4.56,
    5.688,
    4.536,
    5.952,
    9.504,
    5.136,
    3.408,
    8.16,
    8.112,
    4.392,
    2.64,
    3.936,
    7.872,
    7.272,
    5.232,
    9.648,
    4.152,
    3.576,
    18.456,
    5.64,
    3.912,
    2.304,
    3.96,
    5.04,
    10.176
]


Windows記得要先下載ffmpeg,不然會發生錯誤
代碼如下:

import os
import json
from pydub import AudioSegment

# 指定MP3文件所在的文件夹路徑
folder_path = r'path'

mp3_lengths = []

# 取得長度
for i in range(53):
    mp3_path = os.path.join(folder_path, "{}.mp3".format(i))
    audio = AudioSegment.from_file(mp3_path)
    length_in_seconds = len(audio) / 1000
    mp3_lengths.append(length_in_seconds)

# 将字典保存为JSON文件
output_json_path = r'save path'
with open(output_json_path, 'w') as json_file:
    json.dump(mp3_lengths, json_file, indent=4)

print(f'MP3長度已保存到 {output_json_path}')