遍历音乐文件,添加标题,解决导入苹果不显示文件名的问题

遍历音乐文件,添加标题,解决导入苹果不显示文件名的问题
Photo by The New York Public Library / Unsplash

以下是一个Python脚本示例,用于遍历目录并修改音乐文件的元数据标题属性。该脚本使用mutagen库来处理多种音频格式的元数据:

import os
from mutagen import File
from mutagen.easyid3 import EasyID3
from mutagen.flac import FLAC
from mutagen.mp4 import MP4
import argparse

def update_audio_title(file_path):
    try:
        # 获取文件名(不带扩展名)
        base_name = os.path.splitext(os.path.basename(file_path))[0]
        
        # 根据文件类型处理不同格式
        if file_path.lower().endswith('.mp3'):
            audio = EasyID3(file_path)
            audio['title'] = base_name
            audio.save()
            
        elif file_path.lower().endswith('.flac'):
            audio = FLAC(file_path)
            audio['title'] = [base_name]
            audio.save()
            
        elif file_path.lower().endswith(('.m4a', '.mp4')):
            audio = MP4(file_path)
            audio['\xa9nam'] = [base_name]  # 苹果使用的标题字段
            audio.save()
            
        elif file_path.lower().endswith('.wav'):
            audio = File(file_path, easy=True)
            audio.add_tags()
            audio['title'] = base_name
            audio.save()
            
        print(f"成功更新:{file_path}")
        return True
    except Exception as e:
        print(f"处理失败 {file_path}: {str(e)}")
        return False

def process_directory(directory, recursive=False):
    supported_formats = ('.mp3', '.flac', '.wav', '.m4a', '.mp4')
    count = 0
    success = 0

    if recursive:
        for root, _, files in os.walk(directory):
            for file in files:
                if file.lower().endswith(supported_formats):
                    count += 1
                    file_path = os.path.join(root, file)
                    if update_audio_title(file_path):
                        success += 1
    else:
        for file in os.listdir(directory):
            file_path = os.path.join(directory, file)
            if os.path.isfile(file_path) and file.lower().endswith(supported_formats):
                count += 1
                if update_audio_title(file_path):
                    success += 1

    print(f"\n处理完成!共处理 {count} 个文件,成功 {success} 个")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="更新音频文件元数据标题")
    parser.add_argument("directory", nargs='?', default=os.getcwd(),
                       help="目标目录(默认为当前目录)")
    parser.add_argument("-r", "--recursive", action="store_true",
                       help="递归处理子目录")
    
    args = parser.parse_args()

    print(f"正在处理目录:{args.directory}")
    process_directory(args.directory, args.recursive)

使用方法:

  1. 首先安装依赖库:
pip install mutagen
  1. 将脚本保存为audio_metadata_updater.py
  2. 通过命令行运行:
# 处理当前目录
python audio_metadata_updater.py

# 处理指定目录
python audio_metadata_updater.py /path/to/music/folder

# 递归处理子目录
python audio_metadata_updater.py /path/to/music/folder -r

功能说明:

  • 支持格式:MP3、FLAC、WAV、M4A、MP4
  • 标题会自动设置为文件名(不含扩展名)
  • 会跳过无法处理的文件并显示错误信息
  • 支持递归处理子目录
  • 显示处理统计信息

注意事项:

  1. 建议先在一个副本文件夹测试
  2. 某些特殊字符可能导致兼容性问题
  3. 原始元数据不会被备份(如需备份请提前手动备份)
  4. 对于没有元数据容器的格式(如部分WAV文件),可能会自动创建元数据

示例效果:
文件:周杰伦 - 晴天.mp3 ➔ 标题将被设置为:周杰伦 - 晴天

这个脚本会自动保持文件名不变,只修改元数据中的标题字段,这样导入到苹果设备时就会显示正确的标题信息。