我正在尝试编写一些在按下按钮时播放声音的代码,但是如果按下了按钮并且正在播放声音,则声音会暂停并再次播放,而不是只是播放和重叠。
这就是我所拥有的
var sound:alarm = new alarm();
var isPlaying:Boolean = false;
public function Main()
{
button.addEventListener(MouseEvent.CLICK,playSound);
}
public function playSound(e:Event):void
{
if(isPlaying)sound.stop();
sound.play();
isPlaying=true;
}
乍一看似乎可行,但随后我在输出中看到了以下内容因此,尽管stop不是Sound类的方法,但显然可以使用。实现此方法的正确方法是什么?我也一直在想是否可以使用更合适的条件,因为使用此代码,在第一次单击按钮后每次进入函数时都会调用sound.stop(),有没有一种方法可以让我 checkin 实时是否在播放声音?
最佳答案
在您的代码中,函数playSound(e:Event)
应该是playSound(e:MouseEvent);
同样,您正确的stop()
不是Sound
类的方法,但是您不使用Sound
类,而是使用alarm
类(除非警报类扩展了Sound类)。 ,我搜索了google,然后弹出了Flash Play/Pause Sound
更新:
import flash.media.SoundChannel;
// Make sure to import the SoundChannel class
var sc:SoundChannel = new SoundChannel();
var sound:Sound = new alarm();
var isPlaying:Boolean = false;
var pausePos:Number = 0;
public function Main()
{
button.addEventListener(MouseEvent.CLICK,playSound);
}
public function playSound(e:MouseEvent):void
{
if(isPlaying) {
pausePos = sc.position;
sc.stop();
isPlaying = false;
} else {
sc = sound.play(pausePos);
isPlaying = true;
}
}
这段代码应该可以工作,但是我尚未对其进行测试,因此,如果出现任何错误或未达到期望的结果,请告诉我,我会解决的。