Skip to main content
Participant
September 18, 2020
Question

Background Music with On/Off Button

  • September 18, 2020
  • 1 reply
  • 618 views

I have a project and I am at my wits end and have tried everything I can read along with several videos.

 

I have a project that I have already begun, and now I have to build onto it. It's 400 frames in all.

I now have to add background music with a functional button that will stop and start the background music. The music should start playing when the scene begins, but I have NO IDEA how to link the button with the sound to make it start and stop.

I have a picture of a SUN that I would like to use as the on/off button.

What am I doing wrong? I have the music already in its own timeline, playing throughout the 400 frames. I've gotten it to the point to loop back around, to start again from the beginning instead of a new instance beginning over the top of a previously played one.

Button for on/off? Help, please!! 😞

Using Adobe Animate in Action 3.0, newest version.

    This topic is closed to new replies. Start a new post to keep the conversation going.

    1 reply

    JoãoCésar17023019
    Community Expert
    Community Expert
    September 18, 2020

    Hi.

     

    It will be better to call your song from the Library and control it with corresponding AS3 classes. Like this:

     

    AS3 code:

    import flash.events.MouseEvent;
    import flash.media.SoundChannel;
    import flash.media.SoundTransform;
    
    if (!this.frame1Started)
    {
    	var channels:Object = {};
    	var bgmIsPlaying:Boolean = true;
    
    	toggleButton.addEventListener(MouseEvent.CLICK, toggleBGM);
    	// BGM is the linkage name of a sound file in the Library.
    	// "bgm" is a name you give for the channel you want your song to play on. If you need to play simultaneous sounds, give them different channels names
    	// 1 is the volume. The acceptable range is from 0 to 1
    	// 9999 is number of times the song will loop
    	playSound(new BGM(), "bgm", 1, 9999);
    	this.frame1Started = true;
    }
    
    function playSound(sound:*, channel:String, volume:Number = 1, loops:uint = 0):void
    {
    	var soundTransform:SoundTransform = new SoundTransform();
    	
    	if (!channels[channel])
    		channels[channel] = new SoundChannel();
    
    	channels[channel] = sound.play(0, loops);
    	soundTransform.volume = volume;
    	channels[channel].soundTransform = soundTransform;
    }
    
    function stopSound(channel:String):void
    {
    	if (channels[channel])
    		channels[channel].stop();
    }
    
    function toggleBGM(e:MouseEvent):void
    {
    	if (bgmIsPlaying)
    		stopSound("bgm");		
    	else
    		playSound(new BGM(), "bgm", 1, 9999);
    	
    	bgmIsPlaying = !bgmIsPlaying;
    }

     

    FLA / sample / files:

    https://bit.ly/3hGUGNP

     

    Please let us know if you need further assistance.

     

    Regards,

    JC