You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML5 Audio设置currentTime无效的问题及Django环境解决方案

音乐播放器Audio元素currentTime设置失效问题解决(Django场景)

项目中搭建的音乐播放器整体功能正常,但部分MP3文件无法设置Audio元素的currentTime,示例代码如下:

src = "music path";
const audioElement = new Audio(src);
let playPromise = audioElement.play();
if (playPromise!==undefined){
    playPromise.then(function() {
        // promised audio started
        audioElement.currentTime = 20;
        console.log(audioElement.currentTime);

        }).catch(function(error) {
        // promised audio failed
    });
}

程序结果 => 0

设置新的currentTime后,音频从头播放,时间值变为0。确认音频文件正常,时长120秒,问题并非源于时长不足。

经排查,该问题与HTTP响应头配置有关,需正确设置以下参数:

accept-ranges: bytes
Content-Length: BYTE_LENGTH_OF_YOUR_FILE
Content-Range: bytes 0-BYTE_LENGTH_OF_YOUR_FILE/BYTE_LENGTH_OF_YOUR_FILE
content-type: audio/mp3

更新:解决方案

经多日排查解决了问题,这是Django框架用户的常见问题。只需通过FileResponse向客户端发送音乐文件,并配置对应HTTP头:

from django.http import FileResponse
import os

response = FileResponse(Object.mp3)
response["Content-Disposition"] = f"filename={Object.name}.mp3"
response["Content-Type"] = "audio/mp3"
response["Content-Length"] = os.path.getsize(Object.mp3.path)
response["Accept-Ranges"] = "bytes"
return response

请勿遗漏Accept-Ranges和Content-Length配置,这两项至关重要!

内容的提问来源于stack exchange,提问作者Mohammad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 14:00:06