如何在前序函数(sound音频播放函数)执行完成后调用其他函数?
解决方案
Hey there! The core problem here is that browser audio playback is asynchronous — if you just tack yourOtherFunction() at the end of your sound() function, it’ll run immediately, before any of the audio finishes playing. We need to listen for when the audio(s) are done and trigger the next function then. Here are two common approaches based on your use case:
方案1:单个音频播放完成后执行后续函数
If you only need to wait for the initial callon audio to finish before running your loop and subsequent function, you can listen to the ended event on the Audio object:
function sound() { number2 = get.num; // '1002', '2003' 等 sNumber = number2.toString(); output = []; delay = 2000; const callon = new Audio('logo/call.wav'); // 等待初始音频播放完成后再执行后续逻辑 callon.addEventListener('ended', () => { // 执行原有的循环逻辑 for (let i = 0, len = sNumber.length; i < len; i++) { output.push(+sNumber.charAt(i)); console.log(output); switch (output[i]) { case 0: // 这里放你原来每个数字对应的音频逻辑 break; // 补充其他数字的case } } // 现在调用你的其他函数 yourOtherFunction(); }); callon.play(); }
方案2:多个顺序音频全部播放完成后执行后续函数
如果你的switch分支里会为每个数字播放单独的音频,并且希望所有音频按顺序播放完成后再触发后续函数,可以用Promise结合async/await来优雅处理顺序播放:
首先封装一个音频播放的Promise工具函数:
// 封装音频播放,播放完成后resolve Promise,支持播放后延迟 function playAudio(audioPath, delayAfter = 0) { return new Promise((resolve) => { const audio = new Audio(audioPath); audio.addEventListener('ended', () => { if (delayAfter > 0) { setTimeout(resolve, delayAfter); } else { resolve(); } }); audio.play(); }); }
然后将sound函数改写成async函数:
async function sound() { number2 = get.num; // '1002', '2003' 等 sNumber = number2.toString(); output = []; // 先播放初始音频,等待完成 await playAudio('logo/call.wav'); // 遍历每个数字,逐个播放对应音频并等待完成 for (let i = 0, len = sNumber.length; i < len; i++) { const num = +sNumber.charAt(i); output.push(num); console.log(output); // 根据数字匹配对应的音频路径(根据你的实际文件路径调整) let audioPath; switch (num) { case 0: audioPath = 'path/to/0.wav'; break; case 1: audioPath = 'path/to/1.wav'; break; case 2: audioPath = 'path/to/2.wav'; break; // 补充所有需要的数字case default: audioPath = 'path/to/default.wav'; } // 播放当前数字的音频,并且播放完成后等待2000ms await playAudio(audioPath, 2000); } // 所有音频播放完成后,调用你的其他函数 yourOtherFunction(); }
这种方式能确保音频按顺序播放,每一步都等待完成后再继续,最后才触发后续函数,完全符合你“sound函数执行完成后调用其他函数”的需求。
内容的提问来源于stack exchange,提问作者Max13

