Search code examples
pythonmp3urllibid3mutagen

Fetching the title and artist of online MP3 files in Python 2.7


I'm writing a script in Python 2.7 that needs to fetch the title, artist and preferably length (but that's less important), of linked MP3 files. I'm not really sure how to go about doing this, I've tried a few approaches with urllib and mutagen, but none have worked. Well, one worked, but for some reason stopped working. urllib started saying that there were too many values to unpack, I'm not sure why. Here is what used to work:

from urllib import urlopen
from mutagen.mp3 import MP3

def getInfo(url):
    filename, headers = urlopen(url)
    audio = MP3(filename)

That worked fine, and I'm not sure what changed, but I haven't found anything else that worked since. I may have been a bit more vague than I realize here, so please let me know if you need more information. Thank you!


Solution

  • I think, you should download mp3 to aremporary folder. After that, you xan read its information. For example,

    from urllib2 import Request, urlopen
    from mutagen.mp3 import MP3
    
    def getInfo(url):
        start_byte = 0
        end_byte = 5000
        url = Request(url)
        url.add_header('Range', 'bytes=' + str(start_byte) + '-' + str(end_byte))
        filename = urlopen(url)
    
        output = open("test_file.mp3",'wb')
        output.write(filename.read())
        output.close()
        audio = MP3("test_file.mp3")
    
        print audio.info.pprint()
    

    But, this is not real solution. Because, i dont know anything about mp3 file structure, which bytes return id3 header. This is an example to how can implement it.