注: 这里的h5主要是指mobile上的chrome和safari, pc未测试,也不关心。
音效播放,两个方案
- 通过原生的audio标签
<audio src="xxx.mp3" />
优点是android和ios支持,缺点也很明显,无法预加载,且需要用户主动触发才可以播放。
- 通过WebAudio Api来做
cocos2dx中也是封装的这种方法,缺点是大部分android手机不支持,优点是可以预先加载,不需主动触发。
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"> | |
<meta name="full-screen" content="yes"/> | |
<meta name="x5-fullscreen" content="true"/> | |
</head> | |
<body> | |
<button id="playBtn" >点击播放</button> | |
<audio id="audio" /> | |
<script src="/javascripts/sound.js"></script> | |
</body> | |
</html> |
/** | |
* Created by hhuai on 2/12/15. | |
*/ | |
document.addEventListener('DOMContentLoaded', function(){ | |
var audio = document.getElementById('audio'); | |
audio.src="/kiss/res/mua.mp3"; | |
}); | |
var mySource; | |
if('webkitAudioContext' in window){ | |
var audio_ctx = new webkitAudioContext(); | |
function loadMusic(url) { | |
var req = new XMLHttpRequest(); | |
req.open('GET', url, true); | |
req.responseType = 'arraybuffer'; | |
req.addEventListener('load',bufferSound, false); | |
req.send(); | |
} | |
function bufferSound(event) { | |
var request = event.target; | |
audio_ctx.decodeAudioData(request.response, function(buffer){ | |
var source = audio_ctx.createBufferSource(); | |
source.buffer = buffer; | |
source.connect(audio_ctx.destination); | |
// Create a volume (gain) node | |
if(typeof audio_ctx.createGainNode === 'function'){ | |
var volumeNode = audio_ctx.createGainNode(); | |
} else { | |
var volumeNode = audio_ctx.createGain(); | |
} | |
volumeNode.gain.value = 1.0; | |
source.connect(volumeNode); | |
mySource = source; | |
playSound(); | |
}, function(e){ console.log("Error with decoding audio data" + e)}); | |
} | |
loadMusic("/kiss/res/mua.mp3"); | |
} | |
function playSound() { | |
if(mySource) { | |
if(typeof mySource.noteOn === 'function' ) | |
{mySource.noteOn(0);} | |
else | |
mySource.start(); | |
} else { | |
var audio = document.getElementById("audio"); | |
audio.play(); | |
} | |
} | |
document.getElementById("playBtn").addEventListener('click', function(){ | |
playSound(); | |
}); | |