Play only one sound

Problem: more than one sound plays at a time

If you are creating an MP3 player or just have several sounds you want to play using different buttons, a typical problem is that the first sound does not stop when another sound is played. To overcome this we use a Singleton class, which will aloow only one Sound object. The class is shown below.

/*******************************************************
Singleton Class for Sounds
*******************************************************/
package biz.Flashscript.media
{
	import flash.display.Sprite;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;
	public class PlaySound extends Sprite
	{
/*
*
* we declare a private variable, which is
* the instance for an object of this class.
*
*/
		private static var _instance:PlaySound;
		private static var channel:SoundChannel;
		public function PlaySound (pvt:PrivateClass):void
		{
		}
/*
*
* The next function will create the instance. We add one parameter,
* which is the root for the instance to be placed. Only one instance will
* be created at all times, but we can manipulate the instance.
*
*/
		public static function getInstance ():PlaySound
		{
			if (_instance == null)
			{
				_instance = new PlaySound (new PrivateClass());
				trace ('_instance initiated');
			}
			return PlaySound._instance;
		}
/*
* We stop the sound here to finish the former Sound. 
* Then the new Sound object will not overlap with any prviuos sound.
*/
		public function ldSound (url:String):void
		{
			if (channel != null)
			{
				channel.stop ();
			}
/*
* Here we create a new Sound.
*/
			if (url != null)
			{
				var mySound1:Sound = new Sound  ;
				mySound1.load (new URLRequest(url));
				channel = mySound1.play(0,1);
			}
		}
	}
}
/*
* The PrivateClass
*/
class PrivateClass
{
	public function PrivateClass ()
	{
		trace ('PrivateClass called');
	}
}
				

In your fla file you have the following code for three buttons for example.

import biz.Flashscript.media.PlaySound;
import flash.events.*;
var soundArray:Array = new Array('track1.mp3','track2.mp3','track3.mp3');
function startAudio (e:MouseEvent)
{
	var but:Sprite = e.currentTarget as Sprite;
	var myAudio:String;
	var myPath:String = 'mp3/';
	if (but.name == 'button1')
	{
		myAudio = myPath+soundArray[0];
	}
	else if (but.name=='button2')
	{
		myAudio = myPath+soundArray[1];
	}
	else if (but.name=='button3')
	{
		myAudio = myPath+soundArray[2];
	}
	try
	{
		var bb:PlaySound = PlaySound.getInstance(myAudio);
		bb.ldSound(myAudio);
	}
	catch (e:Error)
	{
		trace ('Error');
	}
}
button1.label = 'Track1';
button1.addEventListener (MouseEvent.CLICK, startAudio);
button2.label = 'Track2';
button2.addEventListener (MouseEvent.CLICK, startAudio);
button3.label = 'Track3';
button3.addEventListener (MouseEvent.CLICK, startAudio);