Random Music Player

Hey I want my music player to randomly select songs at all times - NOT just pick a random start song and then play the rest in a predefined order. The script I wrote is just not doing the job and I can’t figure out why. I would REALLY appreciate some assistance.

I have an array that holds ID numbers to each song and after each song is played the ID is removed from the array and then a new random number is picked based on the new length of the array. But it’s not consistent. Can someone PLEASE advise on what I am not understanding?

@script RequireComponent (AudioSource)

var musicTrack : AudioClip[];
private var songID : int = 0;
private var idArray : Array = new Array();

function Start(){
	DontDestroyOnLoad(this);
	audio.loop = false;
	initIdArray();
	songID = idArray[Random.Range(0,idArray.length)];
	PlayMusic();
}

function PlayMusic(){
	while (true){
		audio.clip = musicTrack[songID];
		audio.Play();
		if(audio.clip) {
			yield WaitForSeconds(audio.clip.length);
			idArray.RemoveAt(songID);
			if(idArray.Length == 0){
				initIdArray();
			}
			songID = idArray[Random.Range(0,idArray.length)];
		}
	}
}

function initIdArray(){
	for(var m : int = 0; m < musicTrack.length; m++){
		idArray.Add(m);
	}
}

It works some of the time but usually after 3 or 4 songs it just quits playing music. And sometimes I get an out-of-index error on line 21.

I think I may have fixed the script, although the only way to test it is to listen to all the songs and see if they don’t repeat and no errors are thrown. So far it has been working. I wanted a script that would play music in a random order and not repeat any songs until all had been played. So this is what I got:

@script RequireComponent (AudioSource)

var musicTrack : AudioClip[];
private var songID : int;
private var idArray : Array = new Array();
private var idIndex : int;

function Start(){
	audio.loop = false;
	initIdArray();
	idIndex = Random.Range(0,idArray.length);
	songID = idArray[idIndex];
	PlayMusic();
}

function PlayMusic(){
	while (true){
		audio.clip = musicTrack[songID];
		audio.Play();
		if(audio.clip) {
			yield WaitForSeconds(audio.clip.length);
			idArray.RemoveAt(idIndex);
			if(idArray.length == 0){
				initIdArray();
			}
			idIndex = Random.Range(0,idArray.length);
			songID = idArray[idIndex];
		}
		yield;
	}
}

function initIdArray(){
	for(var m : int = 0; m < musicTrack.length; m++){
		idArray.Add(m);
	}
}