对所有按钮和输入使用事件侦听器来播放 UI 音频

Using event listener for all buttons and inputs to play UI audio

提问人:Freelance Films Scotland 提问时间:11/6/2023 最后编辑:XMehdi01Freelance Films Scotland 更新时间:11/6/2023 访问量:45

问:

想知道这是否可行。

我有各种输入和按钮,我想添加声音。

因此,在我的代码中,我有以下内容:

// Declaring the audio MP3s
        const UISoundInput = document.querySelectorAll("input","button");
        const UISound_Click= new Audio('audio\\\click.mp3';
        const UIsound_delete= new Audio('audio\\\delete.mp3');
        const UISound_error= new Audio('audio\\\error.mp3');
        const UISound_save = new Audio('audio\\\save.mp3');


// Add Event listener for each input          
        UISoundInput.forEach((AudioEvent) =>{
            AudioEvent.addEventListener("input",()=>{
                switch (AudioEvent.className){
// Check input class name and if it's UICLICK Play the audio file at the volume specified by the UI click volume range input value.

             case "UIClick":
                    const UIClickVolume = document.getElementById("Sounds_ClickValue");
                    UISound_Click.volume= UIClickVolume.value/100;
                    console.log (uiclick)
                    UISound_Click.play;
                     ;
                    break
                }

            })
        })

作为一种解决方法,我已经让它作为一个函数工作,但我真的不想每次都不断加载新的音频 src:

    function play() {
        var UISound_Click = new Audio("audio\\\click.mp3");
        const UIClickVolume = document.getElementById("Sounds_ClickValue");
        UISound_Click.volume= UIClickVolume.value/100;
        UISound_Click.play();
    }

下面是HTML

                                                    <div id="Sounds_Click">
                                                        <span> Click</span>
                                                        <input class="UIClick" type="range" min="0" max="100" step="1" value="50" id="Sounds_ClickVolume" oninput="this.nextElementSibling.value = this.value">
                                                        <input class="UIClick" type="number" min="0" max="100" step="1" value="" placeholder="50" id="Sounds_ClickValue" oninput="this.previousElementSibling.value = this.value;play()">
                                                    </div>

谁能帮忙解释为什么这在事件侦听器上不起作用?控制台日志记录显示它确实有效。

任何帮助都会被大力理解,对我放轻松,因为我有点傻!

javascript html addeventlistener html5-audio

评论


答: 暂无答案