2

I am trying to serve MP3 files to django templates which can be used in audio tag. I am using the following view.

def get_file(request):
    filename = FILE_PATH + '\\' + files['k']
    wrapper = FileWrapper(file(filename))
    response = HttpResponse(wrapper, content_type='audio/mp3')
    response['Content-Length'] = os.path.getsize(filename)
    return response

But I am not able to get the file , while I visit the URL corresponding to the view its just serves a zero kb MP3 file.

Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106
  • I am using the following audio tag in a template: {{music}} is from the request url. Can you show your template? – Timo Mar 27 '15 at 07:48

1 Answers1

2

You'll need to open the MP3 file in binary mode:

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

If you open the file in textmode (the default) then various line endings are normalized to \n, which is great for text, but in binary information such as an MP3 file that's a big problem.

Note that I use the open function here, not the file constructor; from the file documentation:

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343