Dynamically positioning a sound with panning in AS3
I'm trying to make a minigame i开发者_如何学JAVAn Flash about a mosquito getting smashed and I want the mosquito sound to pan as if it was in front of the player (so if the mosquito is at the right of the screen pan would be 1, and -1 in the left).
Problem is, I can only use the sound transform in the play method, which leaves me with many sounds playing if I want to update the position of the mosquito (which happens on enterframe, 24fps).
tl;dr, is it possible to pan sounds dynamically in flash?
Certainly is possible and I just happened to be doing something similar the other day.
I created a class that wrapped the sound and added properties for pan, volume etc so that the state could be maintained.
When the sound is played, simply create a new SoundTransform
and assign it to the newly created SoundChannel
. Then, set the pan property on the SoundTransform
based on the pan value in the wrapped up sound class:
public class SoundWrapper
{
private var _pan:Number;
private var _sound:Sound;
private var _soundTransform:SoundTransform;
private var _soundChannel:SoundChannel;
public function SoundWrapper(sound:Sound):void
{
_sound = sound
}
public function playSound():void
{
_soundChannel= _sound.play();
_soundTransform = new SoundTransform();
_soundTransform.pan = pan;
_soundChannel.soundTransform = _soundTransform;
_soundChannel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
}
public function onSoundComplete(e:Event):void
{
playSound();
}
public function stop():void
{
if(_soundChannel)
{
_soundChannel.stop();
_soundChannel.removeEventListener(Event.SOUND_COMPLETE, onSoundComplete);
}
_soundTransform = null;
_soundChannel = null;
}
public function set pan(value:Number):void
{
_pan = value;
if(_soundTransform)
{
_soundTransform.pan = _pan;
}
}
public function get pan():Number
{
return _pan;
}
}
精彩评论