2012-04-29 36 views
0

我有以下的javascript代碼玩一些HTML5的聲音:如果在複選框未選中時如何使用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?] 
    } 
} 

什麼,我需要在這部分增加檢查時,聽到的聲音,而不是選中的時候?我似乎無法得到它的工作。

親切的問候, 莫里斯

+1

您需要點擊監聽器附加到返回現場時,複選框狀態保存在cookie所以複選框 – tskulbru 2012-04-29 11:11:42

+0

,狀態被「記住」,因此不使用點擊功能(在這種情況下)。所以它應該靜音的複選框的條件,因爲我已經嘗試過我的不完整的if語句 – Maurice 2012-04-29 23:58:42

回答

0

沒關係,我解決了這個問題。我想太硬,這是可以做到非常簡單:

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

這工作

相關問題