【问题标题】:DOMException when sending audio file using Django使用 Django 发送音频文件时出现 DOMException
【发布时间】:2019-09-05 17:41:02
【问题描述】:

我正在构建一个基于 Django 的 Web 应用程序,我想通过单击按钮在浏览器中播放来自服务器的音频文件。该文件会随着应用程序的使用而变化,因此我通过 audio 元素的 src 属性调用 Django 视图,如下所示:

<audio id="audio" src="{% url 'play' 'for-sure' %}" type="audio/wav"></audio>

这里for-sure 是默认播放的文件名。这是映射视图函数:

def play(request, file_name):
    with open(f'audio/{file_name}.wav', 'rb') as f:
        response = HttpResponse(f.read(), status=206)
        response['content_type'] = 'audio/wav'
        return response

我还添加了一个按钮来播放声音:

<input type="button" value="Play audio" onclick="play()" id="play_btn">

以及随附的 Javascript:

function play(){
    var audioElement = document.getElementById("audio");
    var promise = audioElement.play();
    if (promise !== undefined) {
      promise.then(_ => {
        console.log('playing')
      }).catch(error => {
        console.log('playing error')
        console.log(error)
        console.log(error.message)
      });
    }
  };

这在 Firefox (v68) 中有效,但我在 Chromium (v76) 中不断收到 DOMException: Failed to load because no supported source was found

据我发现,这似乎是自动播放预防策略,但它在 Firefox 中也应该是有效的。如果是这样,我猜它可能是通过接收想要自动播放音频的视图的 HTTP 响应来触发的。

我也尝试将 AudioContext 初始化为 here,并在单击按钮时恢复它,但无济于事。

我缺少什么以及如何使其发挥作用?

【问题讨论】:

    标签: javascript django audio domexception


    【解决方案1】:

    好的,我终于明白了——毕竟这不是自动播放政策。 Chrome 不支持将音频元素的 src 属性作为 Django 视图的 url(以 HTTP 响应音频文件传输响应)。因此Failed to load because no supported source was found

    作为一种解决方案,我切换到从我的static 目录提供音频文件,将src 设置为静态文件的路径。例如,指向默认声音的音频元素 init 现在显示为:

    <audio id="audio" src="{% static 'annotate/audio/for-sure.wav' %}" type="audio/wav">
    </audio>
    

    【讨论】:

      猜你喜欢
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多