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

点击按钮时如何强制刷新HTML音频播放器缓存加载新in.wav?

问题出在两点:浏览器缓存了旧的in.wav文件,且当前代码中音频加载操作和AJAX生成文件的操作是并行执行的,可能新文件还没生成完播放器就已经加载了旧资源。

解决方法如下:

1. 给音频URL添加随机参数,绕过浏览器缓存

浏览器会根据URL判断资源是否相同,只要URL变化,就会重新请求新资源。我们可以在src后添加时间戳参数,每次点击按钮时更新这个参数。

2. 确保在AJAX请求完成(新文件生成完毕)后再加载音频

把音频加载的逻辑放到AJAX的onSuccess回调里,保证新文件已经生成后再触发播放器加载。

修改后的代码示例:

function display(textString, keyString, modeString, instrumentString, onSuccess) {
    $.ajax({
        url: "string_return",
        data: {
            text_string: textString,
            key_string: keyString,
            mode_string: modeString,
            instrument_string: instrumentString
        },
        dataType: "json",
        type: "GET",
        success: function(response) {
            onSuccess(response);
        }
    });
}

$("#convert-button").on("click", function() {
    let textString = $("#text-input").val();
    let key = $("#key").val();
    let mode = $("#mode").val();
    let inst = $("#instrument").val();

    display(textString, key, mode, inst, function(returnedString) {
        $("#returned_string").text(returnedString);
        
        // 新文件生成后再处理音频加载
        const audio_player = document.getElementById("player");
        // 添加时间戳参数绕过缓存
        audio_player.src = `/static/in.wav?t=${Date.now()}`;
        audio_player.load();
        // 可选:自动播放(如果需要)
        // audio_player.play().catch(err => console.log(err));
    });
});

额外优化:Flask端禁用缓存(可选)

如果不想前端加参数,也可以在Flask设置响应头,禁用in.wav的缓存:

from flask import send_from_directory

@app.route('/static/in.wav')
def serve_audio():
    response = send_from_directory('static', 'in.wav')
    response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '0'
    return response

这样即使URL不变,浏览器也不会缓存该文件,但前端加时间戳的方法更直接,兼容性更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:22:24