42 lines
1.5 KiB
Python
42 lines
1.5 KiB
Python
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
|
|
def create_sorted_m3u_playlist(target_folder: Path):
|
|
|
|
audio_extensions = {'.mp3', '.flac', '.m4a', '.wav', '.ogg', '.wma'}
|
|
|
|
playlist_file = target_folder.parent / f"{target_folder.name}.m3u"
|
|
|
|
music_files = []
|
|
|
|
for file_path in target_folder.rglob('*'):
|
|
if file_path.is_file() and file_path.suffix.lower() in audio_extensions:
|
|
music_files.append(file_path)
|
|
|
|
if not music_files:
|
|
print(f"No music files found in '{target_folder}'.")
|
|
return
|
|
|
|
music_files.sort(key=lambda p: (p.parent, p.name))
|
|
|
|
try:
|
|
with open(playlist_file, 'w', encoding='utf-8') as f:
|
|
f.write("#EXTM3U\n")
|
|
|
|
for file_path in music_files:
|
|
relative_path = file_path.relative_to(target_folder.parent)
|
|
f.write(f"{relative_path.as_posix()}\n")
|
|
|
|
print(f"Success! Created sorted playlist '{target_folder.name}' inside '{target_folder.parent}'.")
|
|
print(f"Added and sorted {len(music_files)} music files.")
|
|
subprocess.run(["gnome-text-editor", str(playlist_file)], check=True)
|
|
except Exception as e:
|
|
print(f"An error occurred while creating the playlist: {e}")
|
|
|
|
# --- How to run it ---
|
|
if __name__ == "__main__":
|
|
music_directory = Path(subprocess.run(["zenity", "--file-selection", "--directory","--filename=/nas/media/music/"],text=True, capture_output=True).stdout.strip())
|
|
|
|
|
|
create_sorted_m3u_playlist(music_directory) |