首页 > 解决方案 > Audio tag playing sound only once, onclick - Safari

问题描述

I was making this little practice project for myself, a drum machine, where you press a button - you get a certain sound. Everything worked fine until I opened it in Safari. It plays the sound once, then it kind of does it after, but the audio sounds glitched and so quiet that I initially thought there was no sound at all. I have attached the link to codepen. Granted, there are no sounds in codepen version as I don't really know where to easily upload them. If someone knows a good way to do that, I will gladly add it as well.

<div data-key="KeyA" class="button flex">
    <h1>A</h1>
    <h2>Kick</h2>
    <audio data-key="KeyA" src="./sounds/kick.wav"></audio>
</div>
<div data-key="KeyS" class="button flex">
    <h1>S</h1>
    <h2>Snare</h2>
    <audio data-key="KeyS" src="./sounds/snare.wav"></audio>
</div>

...

const buttons = document.querySelectorAll('.button');

buttons.forEach(button => {
    button.addEventListener('click', e => {
        const sound = document.querySelector(`audio[data-key="${button.dataset.key}"]`);
        sound.currentTime = 0;
        sound.play();

window.addEventListener('keydown', e => {
    const sound = document.querySelector(`audio[data-key="${e.code}"]`);
    sound.currentTime = 0;
    sound.play();
    boxPress(e);
});

https://codepen.io/onelegtony/pen/qBrwPrP

标签: javascriptaudiosafariplayback

解决方案


推荐阅读