Search code examples
actionscript-3audioairscopesoundchannel

AS3 SoundChannel Position of audio in function


I am having issues with variable scope. I know this must be an easy fix but I can't find it.

I need to play sound through a sound channel in a function. Then I need another function to read the sound channel position. But it is not seeing it because of the new var in the function that plays it. If I play it outside the function I can get the position from another function but if I beging the sound in the function then another function can not read the channel position. How do I fix this.

The Code

import flash.filesystem.File; 
import flash.filesystem.FileMode; 
import flash.filesystem.FileStream;

var lastPosition:Number = 0; var CrossAudio = new Sound();
CrossAudio.load(new URLRequest("Cross.mp3"));

function playCross() {

    PapaAudioChannel = CrossAudio.play();


}
bt_play.addEventListener(MouseEvent.CLICK, playA);

function playA(event:MouseEvent):void    {   
trace(PapaAudioChannel.position);  // Does not work
/// It can't doesn't recognize the PapaAudioChannel because 
 /// it began playing in another function. 

}

How can I get the second function to see the position of the audio. I need to start the audio with a play and pause button so the play has to start in a function.

Thanks


Solution

  • AFAIK the sound can start with a little delay, so tracing sound position just after a play() statement is not a good idea.

    EDIT

    By the way, where is PapaAudioChannel defined, if it is? (it should since this is AS3)

    If you define a var in a function, it dies with that function, at the end of function!

    So you may want to define PapaAudioChannel in the global scope:

    import flash.filesystem.File; 
    import flash.filesystem.FileMode; 
    import flash.filesystem.FileStream;
    
    var PapaAudioChannel:SoundChannel; // defines variable
    
    var lastPosition:Number = 0; var CrossAudio = new Sound();
    CrossAudio.load(new URLRequest("Cross.mp3"));
    
    function playCross() {
    
        PapaAudioChannel = CrossAudio.play();
    
    }
    
    bt_play.addEventListener(MouseEvent.CLICK, playA);
    
    function playA(event:MouseEvent):void {   
    
        trace(PapaAudioChannel.position);
    
    }