0
votes

I am trying to play random sounds from library files(not from external mp3 files). I have created an array of sound objects but when I try to play a sound from the array it is not playing. please help?

var dgSound:Sound = new DogSound();
var lnSound:Sound = new LionSound();
var snSound:Sound = new SnakeSound();
var mySoundArray:Array = new Array("dgSound","lnSound","snSound");
mySoundArray[0].play();

when I play a specific file, it works

2

2 Answers

1
votes
var dgSound:Sound = new DogSound();
var lnSound:Sound = new LionSound();
var snSound:Sound = new SnakeSound();
var mySoundArray:Array = new Array(dgSound,lnSound,snSound);
mySoundArray[Math.floor(Math.random()*mySoundArray.length)].play();

This will accomplish what you want, but for future reference, anything that has quotes around it, like "thing", will be compiled as a text to show to a user, if you want to access the actual variable, then don't use quotes.

Also: Math.floor() just converts any decimal number in it to the floor value of its integer value. EXAMPLE: Math.floor(5.1341) --> 5 and Math.floor(23.9) --> 23. And Math.random() returns a random value between 0 and .999999... and multiplying this by the length of the array makes it so it returns a random decimal value that is in the range of the array, and math floor then cuts it down to access one of the elements.

For Example: If Math.random() return .8562... then you would get:

mySoundArray[Math.floor(.8562*mySoundArray.length)].play();
mySoundArray[Math.floor(.8562*3)].play();
mySoundArray[Math.floor(2.5686)].play();
mySoundArray[2].play();
snSound.play();

.8562 was a pretty high return, and so you ended up getting the last value in the array. I hope i have explained the code that i have given you, please respond if you have any further questions.

0
votes

You should put sound instance in array,not a string type

var mySoundArray:Array = new Array(dgSound,lnSound,snSound );