如何在ActionScript 3.0中按键增加/减少声音的音量
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}
}
}
}
这应该这样做。
答案 2 :(得分: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%
答案 3 :(得分:0)
您需要使用侦听器来侦听KeyboardEvents,例如
http://www.bensilvis.com/?p=146
要改变音量,您需要在播放声音时使用SoundChannel上的SoundTransform,例如。