查看文档
CreateJs整合了SoundJs,看看官方文档说怎么用。
SoundJs文档
理解一下
createjs.Sound.alternateExtensions = ["mp3"];
createjs.Sound.on("fileload", loadHandler, stage);
createjs.Sound.registerSound("path/to/mySound.ogg", "sound");//路径,id
function loadHandler(event) {
// 这会引发针对每个已注册的声音。
// !!!!每注册成功一个声音,都会执行一次!!!
var instance = createjs.Sound.play("sound"); // 发挥使用ID。也可以使用完整的源路径或event.src。
instance.on("complete", handleComplete, stage);// 音乐播放完毕后执行的函数
instance.volume = 0.5;
}
坑
由于谷歌浏览器的一些安全策略,我们无法直接自动播放声音。
经过测试,在火狐浏览器下可以进行自动播放。
把最终的成品挂到服务器上后,谷歌浏览器也可进行正常播放。
所以建议使用火狐进行本地测试。
另一种更好的方式
由于一个游戏中会存在很多音乐音效,所以我们采用createjs.Sound.registerSounds()进行注册,可以方便后续对于音乐的管理和调用。
使用方法如下↓
var assetPath = "sounds/";
var sounds = [
{src:"bgm.mp3", id:"bgm"},
{src:"bulletShooting.mp3", id:"bulletShooting"},
{src:"eat.mp3", id:"eat",data:1},//data控制该声音最大实例数
{src:"fail.mp3", id:"fail"}
];
createjs.Sound.alternateExtensions = ["mp3"];
createjs.Sound.on("fileload", playBgm); // call handleLoad when each sound loads
createjs.Sound.registerSounds(sounds, assetPath);
function playBgm() {
var bgm = createjs.Sound.play("bgm",{loop:-1}); // loop控制循环次数,-1为无限循环
bgm.volume = 0.5;
}
把自己所需的音乐放到assetPath对应的路径中,并把音乐的源和id以数组形式储存在sounds中。
全部注册完毕后,执行监听fileload指定的函数。
这就完成了我们的初始化。
调用注册好的音乐
如图,直接在我们需要用到某个音乐的地方播放他。
在僵尸吃菜中,如果直接这么调用↓
//没死亡,碰到植物
else {
movingZombie.isAttacking = true;
movingZombie.isWalking = false;
movingZombie.isDead = false;
//音乐
var bulletShooting = createjs.Sound.play("eat");
bulletShooting.volume = 0.5;
var attackedPlant = plantContainer.getChildByName("plant_" + movingZombie.zombieRow + "_" + zombieColumn);
attackedPlant.alpha -= 0.01; // 植物逐渐死亡
// 植物死了
if (attackedPlant.alpha < 0) {
plantsArray[attackedPlant.plantRow][attackedPlant.plantCol] = 0; //removes the plant from the array
plantContainer.removeChild(attackedPlant); //removes the plant Display Object from Display List
}
}
会导致在吃菜时的每一帧都生成一个新的吃菜声音,逻辑上是不对的。
所以在最初注册吃菜声音时,我指定了吃菜声音同时播放的最大实例数为1。
带音乐音效的PVZ