2009-12-04 124 views

回答

5
private var sound:Sound; 
private var channel:SoundChannel; 
private const INCREMENT:Number = 0.2;//change it as you like 

sound = new Sound(); 
sound.addEventListener(Event.COMPLETE, onLoad); 
sound.load(new URLRequest("song.mp3")); 

function onLoad(e:Event):void 
{ 
    channel = sound.play(); 
    if(stage) 
    { 
     stage.addEventListener(KeyboardEvent.KEY_UP, onKey); 
    } 
    else 
     trace("call this from a display object on stage"); 
} 
function onKey(e:KeyboardEvent):void 
{ 
    var tr:SoundTransform = channel.soundTransform; 
    var vol:Number = tr.volume; 
    if(e.keyCode == Keyboard.UP) 
     vol += INCREMENT; 
    else if(e.keyCode == Keyboard.DOWN) 
     vol -= INCREMENT; 
    if(vol < 0)//volume ranges from 0 to 1 
     vol = 0; 
    if(vol > 1) 
     vol = 1; 
    tr.volume = vol; 
    channel.soundTransform = tr; 
} 
+0

謝謝!非常清楚 – Dimmduh

1
package { 
import flash.display.Sprite; 
import flash.events.KeyboardEvent; 
import flash.media.Sound; 
import flash.media.SoundChannel; 
import flash.media.SoundTransform; 
import flash.net.URLRequest; 
import flash.ui.Keyboard; 

public class Main extends Sprite 
{ 
    public function Main() 
    { 
    sound = new Sound(new URLRequest("http://assets.flashstall.com/mp3/Estelle - American Boy (sample).mp3")); 
    soundChannel = sound.play(); 

    stage.addEventListener(KeyboardEvent.KEY_UP, stage_onKeyUp); 
    } 

    private const INCREMENT_STEP:Number = .1; 

    private var sound:Sound; 
    private var soundChannel:SoundChannel; 
    private var soundTransform_:SoundTransform = new SoundTransform(); 

    private function stage_onKeyUp(e:KeyboardEvent):void 
    { 
    if(!soundChannel) return; 

    switch(e.keyCode) 
    { 
    case Keyboard.UP: 
    if(soundChannel.soundTransform.volume >= 1) break; 
    soundTransform_.volume = soundChannel.soundTransform.volume + INCREMENT_STEP; 
    soundChannel.soundTransform = soundTransform_; 
    break; 

    case Keyboard.DOWN: 
    if(soundChannel.soundTransform.volume <= 0) break; 
    soundTransform_.volume = soundChannel.soundTransform.volume - INCREMENT_STEP; 
    soundChannel.soundTransform = soundTransform_; 
    break; 
    } 
    } 
} 
} 

這應該這樣做。

+0

這是正確的,但似乎不必要的複雜。 –

1

當您在聲音對象上調用play()方法時,它會返回正在播放的SoundChannel。

var channel:SoundChannel = soundObject.play(); 

然後,您可以使用SoundChannel的soundTransform屬性設置該聲音的音量。

channel.soundTransform = new SoundTransform(0.5); // Sets the volume to 50% 

更多的時候你想控制在你的電影中播放的所有聲音的音量。這可以通過設置SoundMixer類的soundTransform屬性來完成。

SoundMixer.soundTransform = new SoundTransform(0.5); // Sets the global volume to 50%