Search code examples
djangomedia-playermediaelement

Allow users to play mp3 files but don't expose them directly on the web


I want to store some mp3s in a folder which is not public, can't be directly accessed through the web and allow users to hear/download the songs with a browser only if they are logged in.

How can I do that?

I do my web development with Django, but if I know how it works is enough.


Solution

  • I assume you use django. Then you can try something like this:

    from django.conf import settings
    from django.contrib.auth.decorators import login_required
    from django.http import HttpResponse
    
    
    @login_required
    def listen(request, file_name):
        # note that MP3_STORAGE should not be in MEDIA_ROOT
        file = open("%smp3/%s" % (settings.MP3_STORAGE, file_name))
        response = HttpResponse(file.read(), mimetype="audio/mpeg")
        return response
    

    Note that you will get dramatic speed decrease. Using generator to read file in blocks may help to save memory.

    Lazy Method for Reading Big File in Python?