nerdap
nerdap

Reputation: 171

Problems with mp3 streaming using django

I'm trying to figure out how to stream mp3 files using django. I've used some of the code from http://djangosnippets.org/snippets/365/ to help me with this. For some reason, the code below gives me a file smaller in size than the actual file stored on the server. The size shows up correctly in the download window, but the actual file comes out to be much smaller. I've tried sending text files using the code below and it seems to work just fine. I can't seem to figure out what's wrong.

def play_song(request, id):
    song = Song.objects.get(pk=id)
    # song is an object which has a FileField name file
    filepath = os.path.join(MP3_STORAGE, song.file.name).replace('\\', '/')
    wrapper = FileWrapper(file(filepath))
    response = HttpResponse(wrapper, content_type='audio/mpeg')
    response['Content-Length'] = os.path.getsize(filepath.replace('/', '\\'))
    response['Content-Disposition'] = 'attachment; filename=%s' % song.file.name
    return response

Upvotes: 1

Views: 1539

Answers (1)

miles82
miles82

Reputation: 6794

Did you read the comments on http://djangosnippets.org/snippets/365/? Try:

For people on Windows you'll need to specify "read binary" mode for anything other than a text file:

wrapper = FileWrapper(file(filename), "rb")

or

Got this working with a few tweaks:

wrapper = FileWrapper(open(filename, 'rb'))

Upvotes: 2

Related Questions