如何使用javascript在取消选中复选框时关闭HTML5音频

How to use javascript to turn off HTML5 audio when checkbox is unchecked?

本文关键字:HTML5 音频 复选框 javascript 何使用 取消      更新时间:2023-09-26

我有以下javascript代码来播放一些HTML5声音:

    var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list:
        "mp3": "audio/mpeg",
        "mp4": "audio/mp4",
        "ogg": "audio/ogg",
        "wav": "audio/wav"
    }
    function createsound(sound){
        var html5audio=document.createElement('audio')
        if (html5audio.canPlayType){ //check support for HTML5 audio
            for (var i=0; i<arguments.length; i++){
                var sourceel=document.createElement('source')
                sourceel.setAttribute('src', arguments[i])
                if (arguments[i].match(/'.('w+)$/i))
                    sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
                html5audio.appendChild(sourceel)
            }
            html5audio.load()
            html5audio.playclip=function(){
                html5audio.pause()
                html5audio.currentTime=0
                html5audio.play()
            }
            return html5audio
        }
        else{
            return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio")}}
        }
    }
//Initialize two sound clips with 1 fallback file each:
var sound1=createsound("audio/tileSelect.ogg", "audio/tileSelect.mp3")
var sound2=createsound("audio/tileRemove.ogg", "audio/tileRemove.mp3")

使用其他功能中使用的sound1.playclip();我可以播放声音

问题:

我有一个 ID 为sound 的复选框。检查时,应听到声音,否则,不应听到声音。

该复选框的代码当前为:

function playSound() {
    if (document.getElementById('sound').checked){
        [something has to be added here?]
    }
}

我需要在此部分添加什么才能在选中时听到声音,而不是在未选中时听到声音?我似乎无法让它工作。

亲切问候莫里斯

关系,我解决了。我想得太辛苦了,可以很简单:

if (document.getElementById('sound').checked){
                sound1.playclip(); 
            }

这行得通