播放< audio></audio> Django模板中的文件 [英] play <audio></audio> file in django template

查看:91
本文介绍了播放< audio></audio> Django模板中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为此苦苦挣扎,以至于我与抑郁症接壤.

I've been struggling with this for so long that I'm bordering depression.

我有一个名为"Song"的模型,看起来像这样.

I have a model called "Song" that looks like this.

from django.db import models

class Song(models.Model):
    title = models.CharField(max_length=100)
    songfile = models.FileField()
    duration = models.FloatField()
    isPlaying = False

    def __str__(self):
        return self.title

当您从索引页面上载mp3文件时,它会创建此模型的一个实例,并使用以下视图将该文件存储在myapp/songdir/中:

When you upload an mp3 file from the index page, it creates an instance of this model and stores the file in myapp/songdir/ using this view:

def home(request):

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            song_title = request.POST.items()[1][1]
            song_address = 'upnplay/songdir/' + song_title + '.mp3'
            with open(song_address, 'wb+' ) as destination:
                for chunk in request.FILES['file'].chunks():
                    destination.write(chunk)
                audio = MP3(song_address)
                c = Song(title = song_title, songfile = song_address, duration = audio.info.length)
                c.save()
            return HttpResponseRedirect('')
    else:
        form = UploadForm()
    c = {'form': form}
    c.update(csrf(request))
    return render(request, 'index.html', {'form': form})

然后,我有一个名为"choosesong"的模板,该模板显示了从保存的模型实例中获得的歌曲列表:

Then I have a template called "choosesong" that displays a list of songs that I get from the model instances saved:

{% extends 'index.html' %}


{% block content %}
<div class="row">
    {% for song in playlist %}
        <a href="playlist/{{song.title}}/"><h3>{{song.title}} -- {{song.duration}}</h3></a>
    {% endfor %}
</div>

{% endblock %}
{% block form %}{% endblock %}

当我单击其中一个链接时,我希望呈现一个新模板,其中包含一个播放我单击其名称的歌曲的元素.我渲染的模板就是这样的:

When I click on one of this links, I want a new template to be rendered, with a element that plays the song whose name I clicked. The template that I render is this one:

{% extends 'index.html' %}

{% block content %}

<div class='row'>
    {{link}}
    <audio controls>
        <source src="../../{{ link }}" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
</div>

{% endblock %}

我用来提供它的视图如下:

And the view I use to deliver it is the following:

def playAudioFile(request, songtitle):
    name = urllib.unquote(songtitle)
    song = get_object_or_404(Song, title=name )
    return render(request, 'playlist.html', {'link': song.songfile })

由于某种原因,我无法在音频元素中播放歌曲,也不知道还有什么尝试.

For some reason I can't get it to play the song inside the audio element and I don't know what else to try.

谢谢你.

推荐答案

您应该添加MEDIA_ROOT和MEDIA_URL配置.处理事情会很容易.这是您解决问题的方法.

You should add MEDIA_ROOT and MEDIA_URL configuration. It will be easy to handle things. Here is the solution to your problem.

在settings.py中:

In settings.py:

MEDIA_ROOT=os.path.join(BASE_DIR,"songdir")
MEDIA_URL='/media/'

也在settings.py中添加 'django.template.context_processors.media', 在TEMPLATES选项的context_processors中.

Also in settings.py add 'django.template.context_processors.media', in the TEMPLATES option's context_processors.

在project/urls.py中:

In project/urls.py:

from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

然后您可以简单地使用:

Then you can simply use:

{{link.url}} 

而不是将其硬编码到模板文件中.

instead of hardcoding it in your template file.

这篇关于播放&lt; audio&gt;&lt;/audio&gt; Django模板中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆