2013年4月25日 星期四

AS3 Sound管理


自己寫的AS3 sound音效物件

用法:
 // 建立音效物件,如果播放完畢要做處理的話,可以加入cbFunc
  var audio:Audio = new Audio(cbFunc);
//撥放AS連結的音效檔
 audio.playSound("test.mp3");
//重複播放
audio.repeat = true;
//設定音量(0~1)
audio.setSoundVolume(0.5);

 程式碼
------------------------------------------------------------------------------------------------

package com.matis.media
{
import flash.events.Event;
import flash.media.*;
import flash.utils.getDefinitionByName;

public class Audio
{
private var snd:Sound = new Sound();
private var sndCh:SoundChannel;
private var audio:Object;
private var soundVolume:Number;
public var repeat:Boolean;
public var mute:Boolean;
private var parent:Sprite;
private var callback:Function;
private var sndName:String;
public function Audio(_cb:Function)
{
callback = _cb;
setSoundVolume();
}


public function setSoundVolume(_soundVolume:Number = 0.7):void{
soundVolume = _soundVolume;
if(sndCh != null){
var stf:SoundTransform = sndCh.soundTransform;
stf.volume = soundVolume;
sndCh.soundTransform = stf;
}
}


public function stop():void{
if(sndCh != null)
sndCh.stop();
}


public function play(_repeat:Boolean = false):void{
repeat = _repeat;
if(sndCh != null){
sndCh = snd.play(0,1);
sndCh.addEventListener(Event.SOUND_COMPLETE , onPlayOver);
}


}


private function onPlayOver(e:Event):void{
if(repeat){
if(sndCh != null){
sndCh = snd.play(0,1);
var stf:SoundTransform = sndCh.soundTransform;
stf.volume = soundVolume;
sndCh.soundTransform = stf;
sndCh.addEventListener(Event.SOUND_COMPLETE , onPlayOver);
}else
trace("sndCh == null");
}
if(callback != null)
callback();

}



/**撥放音效
* @param sndId 音效類別名稱
* */
public function playSound(sndId:String):void{
if(!mute){
if(sndCh != null && sndName == sndId){
sndCh.stop();
sndCh.removeEventListener(Event.SOUND_COMPLETE , onPlayOver);
sndCh = snd.play(0 , 1);
var stf:SoundTransform = sndCh.soundTransform;
stf.volume = soundVolume;
sndCh.soundTransform = stf;
sndCh.addEventListener(Event.SOUND_COMPLETE , onPlayOver);
}else
setSound(sndId);
}else{
if(sndCh != null)
sndCh.stop();
}
}


public function setSound(sndId:String):void{
var LoadClass:Class = getDefinitionByName(sndId) as Class;
sndName = sndId;
if(LoadClass != null){
var sndObj:Sound = Sound(new LoadClass());
if(sndObj != null){
snd = sndObj;
sndCh = snd.play(0,1);
sndCh.addEventListener(Event.SOUND_COMPLETE , onPlayOver);
var stf:SoundTransform = sndCh.soundTransform;
stf.volume = soundVolume;
sndCh.soundTransform = stf;
}else
trace("Audio","Not found:" + sndId + "讀取音效資源為空值.");
}else{
trace("資源名稱:" + sndId + " 讀取音效資源檔失敗.");
}
}
}
}