SoundJS提供了簡(jiǎn)單而強(qiáng)大的API來處理音頻,大多數(shù)情況下這個(gè)類庫都靜態(tài)方式使用(無需創(chuàng)建實(shí)例)愕把。通過插件來執(zhí)行實(shí)際的音頻實(shí)現(xiàn)拣凹,無需學(xué)習(xí)平臺(tái)相關(guān)的知識(shí)森爽,簡(jiǎn)單直接的處理聲音
使用SoundJS,可以使用Sound類的公開API:
- 安裝回放插件
- 登記聲音
- 創(chuàng)建和播放聲音
- 處理音量咐鹤,靜音拗秘,控制暫停
播放聲音創(chuàng)建SoundInstance實(shí)例,可以單獨(dú)控制祈惶,例如:
- 暫停雕旨,繼續(xù),查找和停止
- 控制音量捧请,靜音等
- 監(jiān)聽聲音實(shí)例的相關(guān)事件并且當(dāng)播放完畢凡涩,循環(huán)或者失敗時(shí)得到提示
下面是最少的代碼實(shí)現(xiàn)聲音播放:
createjs.Sound.initializeDefaultPlugins();
createjs.Sound.alternateExtensions = ["ogg"];
var myInstance = createjs.Sound.play("IntoxicatedRat.mp3");
以上代碼在IE中可以工作,但是在firefox和chrome上不支持疹蛉,缺省使用的是webAudio活箕,我們需要等級(jí)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 = "加載完畢,點(diǎn)擊播放";
audioLabel.x = 175 - audioLabel.getMeasuredWidth() / 2;
audioLabel.y = 200;
audioStage.on("stagemousedown",playAudio,null,false);
audioStage.update();
}