Basically I have two buttons on/off. If I click the button ON more than once while the sound is playing the OFF button doesn't work any more so I am unable to stop the sound. Can someone help?
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.MouseEvent;
var mySound:Sound = new Classical_snd();
var myChannel:SoundChannel = new SoundChannel();
myChannel.stop();
soundON_btn.addEventListener(MouseEvent.CLICK, soundON);
function soundON(event:MouseEvent):void{
myChannel = mySound.play();
}
soundOFF_btn.addEventListener(MouseEvent.CLICK,soundOFF);
function soundOFF(event:MouseEvent):void{
myChannel.stop();
}
The reason why this is happening is because every time you call mySound.play()
a new SoundChannel object to play back the sound is generated and returned by that function call. So if you call it twice, the most recent SoundChannel object is stored in your myChannel
variable; however, any earlier SoundChannel
object that was generated is lost because you no longer have a reference to it and it continues to play.
I would try this:
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.MouseEvent;
var mySound:Sound = new Classical_snd();
var myChannel:SoundChannel = new SoundChannel();
myChannel.stop();
var musicPlaying:Boolean = false;
soundON_btn.addEventListener(MouseEvent.CLICK, soundON);
function soundON(event:MouseEvent):void{
if( !musicPlaying ) {
myChannel = mySound.play();
musicPlaying = true;
}
}
soundOFF_btn.addEventListener(MouseEvent.CLICK,soundOFF);
function soundOFF(event:MouseEvent):void{
myChannel.stop();
musicPlaying = false;
}