I have the following javascript code to play some HTML5 sounds:
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")
With sound1.playclip();
used in other functions I can play the sounds
The problem:
I have a checkbox with ID: sound
. When checked, the sound should be heard, if not, no sound should be heard.
The code for the checkbox currently is:
function playSound() {
if (document.getElementById('sound').checked){
[something has to be added here?]
}
}
What do I need to add in this part to hear the sound when checked and not when unchecked? I can't seem to get it working.
Kind regards, Maurice
Nevermind, I solved it. I was thinking too hard, it can be done very simple:
if (document.getElementById('sound').checked){
sound1.playclip();
}
This works
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.