如何在 onclick 事件中使用两个函数调用 Alert 之前在 Javascript 中播放音频?

问题描述 投票:0回答:1

我们在 Javascript 中动态创建按钮,或者为 Web 应用程序中的所有按钮创建隐藏代码......整个应用程序中有数千个按钮。 该构建的一部分是 onclick=somefunction() 部分。 我想在调用指定的 onclick 函数之前播放音频声音(点击)。因此,不要像这样构建字符串:

s = '<input type="button" onclick="somefunction()"...

我会像这样构建它:

s = '<input type="button" onclick="playSystemSound(link); somefunction()"...
$('btnX').innerHTML = s;

但是,某些被调用的函数中存在警报,这会停止播放声音,直到警报被清除。我显然不能将对 playSystemSound 的调用放在被调用的函数中,太多了。所以,我想我可以使用异步函数并在调用“somefunction()”之前等待它,但它仍然等待警报被清除。 使用上面的示例调用这两个函数,我的代码如下所示:

async function playSystemSound(link) {
    const audio = new Audio(link)
    await playSystemSoundEx(audio);
}

function playSystemSoundEx(audio) {
    return new Promise(res=>{
        audio.play()
        audio.onended = res
    })
}

因此,鉴于我必须在现有功能之前添加一个功能,我的问题是:如何在继续下一个功能之前播放声音?

编辑: 我应该补充一点,我首先尝试了设置超时,因为这通常适用于此类事情。 该代码看起来像:

function playSystemSound(link) {
    setTimeout('playSystemSoundEx("' + link + '")', 50);
}

function playSystemSoundEx(link) {
    const audio = new Audio(link)
    audio.play();
}
javascript event-handling html5-audio
1个回答
0
投票

播放声音后即可调用第二个函数。在示例中,我使用

ended
事件,但可能还有其他事件。这个技巧要求您可以将第二个函数的名称转换为函数调用。这里我使用一个带有命名函数的对象。

const functions = {
  func1: e => {
    alert('Alert from func1');
  },
  func2: e => {
    alert('Alert from func2');
  }
};

document.querySelectorAll('button').forEach(button => {
  button.addEventListener('click', playSystemSoundEx, true);
});

function playSystemSoundEx(clickevent) {
  let secondFunc = functions[clickevent.target.dataset.func];
  const audio = new Audio('https://cdn.pixabay.com/audio/2022/03/24/audio_719bb3b0e5.mp3');
  audio.addEventListener('ended', endevent => {
    //call second function
    secondFunc();
  });
  audio.play();
}
<button data-func="func1">Button 1</button>
<button data-func="func2">Button 2</button>
<button data-func="func1">Button 3</button>
<button data-func="func2">Button 4</button>

© www.soinside.com 2019 - 2024. All rights reserved.