mutagen icon indicating copy to clipboard operation
mutagen copied to clipboard

Can I sort by track number?

Open kubinka0505 opened this issue 2 years ago • 1 comments

Is it possible to sort existing files list with mutagen with TRCK ID3 tag as the key? Does that module have any available iterators that I could use?

I'm not embedding code since I don't know how to do it. Any ideas?

~~I mean, I could create dictionary with track number as key and file as value, but I think that there can be some easier solution to this.~~

kubinka0505 avatar Aug 03 '23 17:08 kubinka0505

Python has the sorted function. If files is a list of mutagen.mp3.MP3 files you could do something like:

def get_tracknumber(file): 
    if trck := file.tags['TRCK']:
        number, total = trck.text[0].split('/')
        try:
            return int(number)
        except ValueError:
            return number

sorted_files = sorted(files, key=get_tracknumber)

Getting the tracknumber from TRCK needs a bit more effort, since according to the ID3 spec this get contain the total number of tracks as well, with track no. and total tracks separated by a slash. Also some people store non-number values in this tag, such as A / B for the sides of Vinyl singles, or track numbers like A1, A2. The above code handles this by returning the number string verbatim in this case.

If you use mutagen.easyid3.EasyID3 you can access the content of TRCK with file['tracknumber'] instead, which simplifies the above code a bit. But you still need to be aware that the total tracks can be part of the tag.

Have a look at https://docs.python.org/3/howto/sorting.html for more details on how to do sorting in Python.

phw avatar Sep 15 '23 12:09 phw