Search code examples
actionscript-3adobe-animate

Stopping sound when going to next frame- Adobe Animate/AS3


I have three frames, each has their own animation movie clip in them. To get to the next scene, you press a button on the current scene, and it goes to frame two.

I have audio in each of the three movie clips, but when I click on the button to go to scene two, the audio from scene 1 keeps playing.

How can I make it so when I click to go to frame two, the audio from frame 1 movie clip stops, and the frame 2 movie clip audio starts?


Solution

  • Make sure you have a SoundChannel attached to your Sound object.

    Then simply assign a soundChannel.stop() in the next button function.

    Frame 1:

    //create a sound class to hold the sound
    var f1sound:Sound = new Sound();
    //soundchannel to control your sound to play and pause
    var sChannel:SoundChannel = new SoundChannel();
    
    //this setup function will load and autoplay your sound file
    function setUp():void {
        f1sound.load(new URLRequest("frame1sound.mp3")); //load your sound file
        f1sound.play();
    
        //add the event for the Next Button, remember to change it to your actual button name
        nextButton.addEventListener(MouseEvent.MOUSE_DOWN, nextBtnDown);
    }
    
    function nextBtnDown():void {
        nextButton.removeEventListener(MouseEvent.MOUSE_DOWN, nextBtnDown);
        sChannel.stop(); //this stop the audio
        f1sound.close(); //this unloads the sound stream for cleaning purposes
    
        gotoAndStop(2); //go to frame 2, put this as the last line of the function
    }
    
    setUp();  //this will make the program run setUp function on the first run, once.
    

    The next frame is basically the same thing as this one, as long as you maintain this format no matter which frame you jump to, back and forth, it should work. There are other optimisations to be done like only play the audio after it has completely loaded, but I'll leave them for you to find out and explore. Good luck.