要使用Python获取MP3文件的信息,可以使用pymediainfo包。
首先,你需要安装pymediainfo。
下面是获取一首歌曲信息的例子
"""
Module to demonstrate how to use `pymediainfo` to read metadata from a media file.
In this module, we read the metadata of a given MP3 file and display the artist's name and
other general information.
In order to use this module, you need to have `pymediainfo` installed.
"""
def read_mp3_metadata(base_dir, mp3_file):
"""
Reads metadata of the given MP3 file.
Args:
base_dir (str): The base directory where the MP3 file is located.
mp3_file (str): The name of the MP3 file.
Returns:
None
"""
# Join the base directory and the file name to form the full path.
mp3_file_path = os.path.join(base_dir, mp3_file)
# Parse the media file using `pymediainfo`.
media_info = MediaInfo.parse(mp3_file_path)
# Print the artist's name.
performer = media_info.tracks[0].to_data()['performer']
print(f"Artist: {performer}")
# Print the metadata of each track.
for track in media_info.tracks:
if track.track_type == "Audio":
print(f"{'-' * 20} Audio Track {'-' * 20}")
for key, value in track.to_data().items():
print(f"{key}: {value}")
if track.track_type == "General":
for key, value in track.to_data().items():
print(f"{key}: {value}")
# Example usage of the function.
read_mp3_metadata(r'C:\Users\user\Desktop\LX-Music', '2002年的第一场雪 - 刀郎.mp3')
注意, 简单的解析歌曲之后,基本信息在media_info.tracks[0]里面, 其实是 track.track_type == "General"里面
所以对歌曲分类的思路就是:
遍历指定目录的歌曲
获取每首歌曲的信息,这里指的是歌手的名字
同一个歌手的放一起
对同一个歌手创建文件夹,并将其对应个歌曲创建软链接放进去
import os
from pymediainfo import MediaInfo
def traverse_music(music_path):
"""
Traverse the files in directory 'music_path'
and read the music file's info with pymediainfo,
create soft link for each file,
and put soft link into a same new folder when have same artist
Args:
music_path (str): The path of the music directory
Returns:
None
"""
# Dictionary to store the mapping between artist and files
artist_dict = {}
# Traverse the files in the directory
try:
for root, dirs, files in os.walk(music_path):
for file in files:
# Skip the file if it is not a mp3 file
if not file.endswith('.mp3'):
continue
# Get the full path of the file
file_path = os.path.join(root, file)
try:
# Read the music info of the file
music_info = MediaInfo.parse(file_path)
# Get the artist of the music
artist = music_info.tracks[0].to_data()['performer']
# If the artist is new, create a new key in the dictionary
if artist not in artist_dict:
artist_dict[artist] = []
# Append the file to the list of files of the artist
artist_dict[artist].append(file_path)
except Exception as e:
print(f"Exception occured while processing {file_path}: {e}")
except Exception as e:
print(f"Exception occured while traversing {music_path}: {e}")
# Print the dictionary
print(artist_dict)
# For each artist, create a new folder and create soft links to files
for artist, files in artist_dict.items():
# Get the path of the artist's folder
artist_path = os.path.join(music_path, artist)
try:
# Create the folder and ignore if it already exists
print('start to create new folder: ', artist_path)
os.makedirs(artist_path, exist_ok=True)
# For each file, create a soft link in the artist's folder
for file in files:
os.symlink(file, os.path.join(artist_path, os.path.basename(file)))
except Exception as e:
print(f"Exception occured while processing {artist_path}: {e}")
traverse_music(r'C:\Users\emijnae\Desktop\LX-Music')
标签:artist,python,歌手,track,music,mp3,file,path,链接
From: https://www.cnblogs.com/aifengqi/p/18517862