Search code examples
actionscript-3flashdevelop

How to specify an end time for a Sound


With the Sound.play function, you can specify a start time in milliseconds as one of the arguments, as well as the number of times to loop the sound. Am I missing something, or is there not a way to specify an end time? For example, if I want the loop milliseconds 5-105 of a 4 second sound, is there a way to specify it to start the next loop at 105 milliseconds?

If I'm not missing something, is there another way to go about this?


Solution

  • The Sound class doesn't allow you to perform that operation, the best way to do this is by using a Timer:

    var musicTimer:Timer = new Timer(100, 5); // Loop total time(ms), N Loops (+1)
    musicTimer.addEventListener(TimerEvent.TIMER, musicTimer_tick);
    musicTimer.addEventListener(TimerEvent.TIMER_COMPLETE, musicTimer_complete);
    musicTimer.start();
    
    private function musicTimer_complete(e:TimerEvent):void 
    {
        // Last loop stop all sounds
        channel.stop();
    }
    
    private function musicTimer_tick(e:TimerEvent):void 
    {
        // At each loop, stop and (re)start the sound
        channel.stop();
        channel = sound.play(5); // 5 is the loop start time
    }