在多次调用的函数中递增全局变量

时间:2010-10-31 13:42:01

标签: flex flash actionscript-3 audio mp3

我正在尝试使用flash创建一个简单的MP3播放器。使用包含歌曲列表的XML文件加载歌曲。以下代码将插入到新的关键帧中。

import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.*;
import flash.events.MouseEvent;
import flash.net.URLRequest; 
import flash.xml.*;

/* Defining The Elements and Variables of the Music Player */
var MusicLoading:URLRequest;                        
var music:Sound = new Sound();
var sc:SoundChannel;
var currentSound:Sound = music;
var CurrentPos:Number;                              
var xml:XML;
var songlist:XMLList;                               
var currentIndex:uint;                              
var XMLLoader:URLLoader = new URLLoader();          
/* ------------------------------------------------------ */


/* --------------------Load songs from the list-------------------- */
function success(e:Event):void 
{
    xml = new XML(e.target.data);
    songlist = xml.song;    //For adding a new song in XML File.
    MusicLoading = new URLRequest(songlist[0].file);
    music.load(MusicLoading);
    currentIndex = 0;
}
//If XML File Load successfully, it will be voided this actions:
XMLLoader.addEventListener(Event.COMPLETE, success);

//The Name of the XML File.
XMLLoader.load(new URLRequest("playlist.xml"));

//Play The Song
function playSong(e:Event):void 
{
    if(sc != null)
        sc.stop();

    sc = currentSound.play(CurrentPos);
}

//Pause The Song
function pauseSong(e:Event):void 
{
    CurrentPos = sc.position;
    sc.stop();
}


//Next Song Functions
function nextSong(e:Event):void 
{
    sc.stop();

trace(currentIndex + " ");

    currentIndex = currentIndex + 1;

    trace(currentIndex);

    var nextSongFunc:URLRequest = new URLRequest(songlist[currentIndex].file);
    var nextTitle:Sound = new Sound();
    nextTitle.load(nextSongFunc);
    currentSound = nextTitle;
    sc = currentSound.play();

    sc.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

PauseBtn.addEventListener(MouseEvent.CLICK, pauseSong);
PlayBtn.addEventListener(MouseEvent.CLICK, playSong);
NextBtn.addEventListener(MouseEvent.CLICK, nextSong);

这里的问题在于nextSong()函数。我无法保留currentIndex的值。虽然每次调用函数时我都会递增currentIndex,但值保持不变。请建议......

1 个答案:

答案 0 :(得分:0)

由于您的变量是在关键帧中定义的,因此每次命中关键帧时都会重新启动它。我敢打赌,在关键帧范围之外移动定义会有所帮助。例如,对于Flash的根(虽然在OOP方面不太好)