# Toggle on/off music button in a closed loop

**URL:** https://forum.kirupa.com/t/toggle-on-off-music-button-in-a-closed-loop/332026
**Category:** flash
**Created:** [January 4, 2014, 2:54am UTC](https://forum.kirupa.com/t/toggle-on-off-music-button-in-a-closed-loop/332026 "2014-01-04T02:54:05Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![rozwaz](https://avatars.discourse-cdn.com/v4/letter/r/dec6dc/32.png) [@rozwaz](https://forum.kirupa.com/u/rozwaz)
#### Post date: [January 4, 2014, 2:54am UTC](https://forum.kirupa.com/t/toggle-on-off-music-button-in-a-closed-loop/332026/1 "2014-01-04T02:54:05Z")

</div>

Hello!  
I’m only really a beginner using Actionscript and have just spent the last few hours writing out some code for a play/pause button that toggles between the play and pause state when clicked. However only afterwards realizing i need to run it in a closed loop (of about 2 or 3 frames) and when this is done, it triggers the audio over and over about a thousand times a second as its just running the code over and over.

I’m fairly certain this is not possible, is there anything i can add so that it will run as I want to in a closed loop?  
Thanks, Rory

[SIZE=6]Code:[/SIZE]

import flash.media.SoundChannel;  
import flash.events.MouseEvent;  
import flash.events.Event;

var soundplaying:Boolean = true;  
var lastposition:Number = 0;  
var mysound:drumnbass = new drumnbass();  
var soundchannel:SoundChannel = new SoundChannel ();

soundchannel = mysound.play(0,2);

soundchannel.addEventListener(Event.SOUND\_COMPLETE, onPlaybackComplete);  
function onPlaybackComplete(event:Event):void  
{  
lastposition = 0;  
soundchannel.stop();  
playpausebutton1.pausebutton1.visible = false;  
soundplaying = false;  
}

playpausebutton1.addEventListener(MouseEvent.CLICK, playsound);  
function playsound(event:MouseEvent) :void  
{  
if (soundplaying = false)  
{  
soundchannel = mysound.play(lastposition, 2);  
playpausebutton1.pausebutton1.visible = true;  
soundplaying = true;  
}  
else  
{  
lastposition = soundchannel.position;  
soundchannel.stop();  
playpausebutton1.pausebutton1.visible = false;  
soundplaying = false;  
}

```
soundchannel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete1);
function onPlaybackComplete1(event:Event):void
{
    lastposition = 0;
    soundchannel.stop();
    playpausebutton1.pausebutton1.visible = false;
    soundplaying = false;
}

```

}
