SoundJS提供了簡單而強大的API來處理音頻,大多數(shù)情況下這個類庫都靜態(tài)方式使用(無需創(chuàng)建實例)。通過插件來執(zhí)行實際的音頻實現(xiàn),無需學(xué)習(xí)平臺相關(guān)的知識,簡單直接的處理聲音
使用SoundJS,可以使用Sound類的公開API:
- 安裝回放插件
- 登記聲音
- 創(chuàng)建和播放聲音
- 處理音量,靜音,控制暫停
播放聲音創(chuàng)建SoundInstance實例,可以單獨控制,例如:
- 暫停,繼續(xù),查找和停止
- 控制音量,靜音等
- 監(jiān)聽聲音實例的相關(guān)事件并且當(dāng)播放完畢,循環(huán)或者失敗時得到提示
下面是最少的代碼實現(xiàn)聲音播放:
createjs.Sound.initializeDefaultPlugins();
createjs.Sound.alternateExtensions = ["ogg"];
var myInstance = createjs.Sound.play("IntoxicatedRat.mp3");
以上代碼在IE中可以工作,但是在firefox和chrome上不支持,缺省使用的是webAudio,我們需要等級HTMLaudio,如下:
createjs.Sound.registerPlugins([ createjs.HTMLAudioPlugin]);
console.log(createjs.Sound.activePlugin.toString());
createjs.Sound.alternateExtensions = ["ogg"];
var mySound = createjs.Sound.play("IntoxicatedRat.mp3");
以上代碼中如果無法加載MP3的話,我們使用alternateExtensions屬性來加載文件OGG。
使用示例:
var audioLabel;
var audioStage;
window.addEventListener("load", initAudioDemo, false);
function initAudioDemo() {
audioStage = new createjs.Stage(document.getElementById("myCanvas"));
startAudioDemo();
}
function startAudioDemo() {
audioDemoIndex = 0;
audioLabel = new createjs.Text("加載中...", "24px microsoft yahei", "#dd4814");
audioLabel.x = 175 - audioLabel.getMeasuredWidth() / 2;
audioLabel.y = 200;
audioStage.addChild(audioLabel);
var loader = new createjs.LoadQueue(true);
loader.installPlugin(createjs.Sound);
loader.on("complete", readytoplayAudio);
loader.loadFile({id:"mysound", src:"http://www.gbtags.com/tutorials/html5-tutorial/html5-demos/assets/song.ogg"});
audioLabel.text = "加載中...";
audioStage.update();
}
function playAudio() {
createjs.Sound.play("mysound");
audioStage.update();
}
function readytoplayAudio() {
audioLabel.text = "加載完畢,點擊播放";
audioLabel.x = 175 - audioLabel.getMeasuredWidth() / 2;
audioLabel.y = 200;
audioStage.on("stagemousedown",playAudio,null,false);
audioStage.update();
}