簡體   English   中英

取消選中復選框時,如何使用JavaScript關閉HTML5音頻?

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

我有以下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(); 
            }

這有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM