Search code examples
actionscript-3flashadobemp3audio

Play sound when number changes in external file


Play mp3 sound if number in external file on server change from 0 to 1 is this possible that flash reads external file changes ever 2 minutes


Solution

  • I think what you're really asking about here has nothing to do with playing an mp3, but rather how to poll a file hosted on a server.

    First, you'd want some kind of a timer. When that timer goes off, you load the file using a URLLoader. You then check the contents of the loader to see if the value has changed to 1:

    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.events.Event;
    
    var currentValue:int = 0;
    var fileLoader:URLLoader = new URLLoader();
    var fileRequest:URLRequest = new URLRequest("url_of_your_file");
    fileLoader.addEventListener(Event.COMPLETE, onLoadComplete);
    // you prbably also want to handle errors (if the file doesn't exist)
    
    var pollTimer:Timer = new Timer(120000); // 120,000 milliseconds = 2 minutes
    pollTimer.addEventListener(TimerEvent.TIMER, pollFile);
    
    pollFile(null); // initial call to pollFile
    pollTimer.start(); // subsequent calls to pollFile
    
    function pollFile(e:TimerEvent):void 
    {
        fileLoader.load(fileRequest);
    }
    
    function onLoadComplete(e:Event):void 
    {
        if(!currentValue && int(fileLoader.data) == 1)
        {
            // the value of the file has changed from 0 to 1 
            // execute your mp3 playing code here
        }
        currentValue = int(fileLoader.data);
    }
    

    EDIT: Reading your comments, it's possible that your request is getting cached and therefore returning the same value every time. There is a bit of a trick to requesting non-cached data:

    // when you create your request, add a query string (noCache) that will change every time.
    var fileRequest:URLRequest = new URLRequest("url_of_your_file?noCache=" + new Date().time);
    
    function pollFile(e:TimerEvent):void 
    {
        // update the value of noCache every time you load the request
        fileRequest.url = fileRequest.url.split("?")[0] + "?noCache=" + new Date().time;
        fileLoader.load(fileRequest);
    }