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

如何修改CreateJS音频播放逻辑实现每15秒播放一次?

解决方案

你的问题出在setTimeout的参数使用错误:直接调用createjs.Sound.play(...)会立即执行播放逻辑,而非延迟执行。下面提供两种符合需求的实现方案:

方案一:固定15秒间隔重复播放(不管音频时长)

适合音频时长短于15秒,且允许可能的音频重叠的场景:

function handleLoad(event) {
    // 首次立即播放
    playSound();
    // 之后每隔15秒自动播放
    setInterval(playSound, 15000);
}

// 封装播放逻辑
function playSound() {
    createjs.Sound.play("pain", {interrupt: createjs.Sound.INTERRUPT_ANY});
}

handleLoad();

方案二:音频播放完成后等待15秒再播放(避免重叠)

如果音频时长可能超过15秒,或者希望播放完一次再等待,用这种方式更合理:

function handleLoad(event) {
    // 启动循环播放逻辑
    playSoundWithDelay();
}

function playSoundWithDelay() {
    var audioInstance = createjs.Sound.play("pain", {interrupt: createjs.Sound.INTERRUPT_ANY});
    
    // 监听音频播放完成事件
    audioInstance.on("complete", function() {
        // 播放结束后等待15秒,再调用自身实现循环
        setTimeout(playSoundWithDelay, 15000);
    });
}

handleLoad();

错误原因说明

你之前的写法:

var myInstance = setTimeout(createjs.Sound.play("pain", {interrupt: createjs.Sound.INTERRUPT_ANY, loop:-1}),15000);

问题在于createjs.Sound.play(...)是立即执行的函数调用,它的返回值会被当作setTimeout的回调函数,而非延迟执行这个播放动作。必须将播放逻辑包裹在函数中,才能让setTimeout在指定时间后执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:10:34