javascriptdjangomp3django-staticfilescollectstatic

How can I play a static mp3 file on static Javascript on a Django application?


In my Django Application, I am trying to play a mp3 file in a function in my javascript file. This JS file is loaded statically by command collectstatic from Django. I couldn't find a way to reference this mp3 file. Both are in the same folder in server-side. I'm thinking that I can only reference this file if it was upload in the page like other image, js or css file. There is a way to load this file to the browser in a Django application with its templates organization?


Solution

  • You should be able to pass the file to an HTML5 audio control using static like this:

    <audio>
      <source src="{% static 'file.mp3' %}" type="audio/mpeg">
    </audio>
    

    Don't forget to {% load staticfiles %} at the top of your template.

    Depending on whether these audio files change a lot it might be more appropriate to treat them as media files rather than static files. You can consult the Django documentation on static and media files for more information on the difference.