Anurag-Sharma
Anurag-Sharma

Reputation: 4398

Playing audio through audio tag in a Django application

How do i use the audio tag of html 5 to play a audio file that has been uploaded in a my django based application.
models.py - Link
settings.py - Link

In my templates i am using the audio tag in the following way -

    {% for file in audio %}
    <li>
    <h4>{{ file.title }}</h4>
    <div id="name"><a href="{{ file.audio_file }}" target="_blank">{{ file.name }}</a></div>
    <div id="play"><audio src="{{ file.audio_file }}" controls="controls">
      Your browser does not support the audio element.
    </audio></div>
    </li>
   {% endfor %}

But I am not able to play the file.

Upvotes: 0

Views: 3266

Answers (1)

nattster
nattster

Reputation: 854

Based on your settings, you cannot play the file because:

  • {{ file.audio_file }} returns value saved in the database, which is absolute path to media file, e.g. http://localhost:8000/Users/test/django_app/media/test.wav

To solve this, you need to:

  1. Edit your models.py

    class AudioFile(models.Model): audio_file = models.FileField(upload_to="music")

    upload_to -- A path that will be appended to your MEDIA_ROOT setting to determine the value of the url attribute

  2. In your template, use {{ file.audio_file.url }} to correctly reference the URL of the uploaded file

  3. You may need to delete existing files, because wrong path was saved in the database.

Upvotes: 1

Related Questions