I am trying to create a simple music player with three songs, with a play button, a stop button, next and previous song buttons. It runs great, except for one flaw: If I click the play button while a sound is already playing, it will play anyway, and overlap on top of the first sound (very unpleasant). Here’s the code I am using:
var my_songs:XMLList;
var my_total:Number;
var my_sound:Sound;
var my_channel:SoundChannel;
var current_song:Number = 0;
var song_position:Number;
var isPlaying:Boolean = false;
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("playlist.xml"));
myXMLLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void
{
var myXML:XML = new XML(e.target.data);
my_songs = myXML.SONG;
my_total = my_songs.length();
playSong(0);
myXMLLoader.removeEventListener(Event.COMPLETE, processXML);
myXMLLoader = null;
}
function playSong(mySong:Number):void
{
var myTitle = my_songs[mySong]. @ TITLE;
var myURL = my_songs[mySong]. @ URL;
title_txt.text = myTitle;
if (my_channel)
{
my_channel.stop();
my_channel.removeEventListener(Event.SOUND_COMPLETE, onNext);
}
my_sound = new Sound();
my_sound.load(new URLRequest(myURL));
my_channel = my_sound.play();
my_channel.addEventListener(Event.SOUND_COMPLETE, onNext);
}
next_btn.addEventListener(MouseEvent.CLICK, onNext);
function onNext(e:Event):void
{
current_song++;
if (current_song >= my_total)
{
current_song = 0;
}
playSong(current_song);
}
prev_btn.addEventListener(MouseEvent.CLICK, onPrev);
function onPrev(e:MouseEvent):void
{
current_song--;
if (current_song < 0)
{
current_song = my_total - 1;
}
playSong(current_song);
}
stop_btn.addEventListener(MouseEvent.CLICK, stopMusic);
function stopMusic(e:Event):void
{
if(my_channel != null)
{
my_channel.stop();
isPlaying = false;
}
}
play_btn.addEventListener(MouseEvent.CLICK, playMusic);
function playMusic(e:Event):void
{
if (!isPlaying)
{
my_channel = my_sound.play();
isPlaying = true;
}
}
How can I fix this? Thanks.