Skip to main content
Participating Frequently
October 22, 2018
Answered

Play random sound

  • October 22, 2018
  • 2 replies
  • 856 views

I have imported 4 songs into the Adobe Animate CC library, and I want to randomly play one of these songs via AS3.

I have given them class-names: "music_1", "music_2", "music_3" and "music_4"

I am trying something like this:

var mySound:Sound = new music_[Math.floor(Math.random() * 4 + 1)]();

mySound.play();

(It gives an error: "Access of undefined property music_.")

With ActionScript 2, I could do this:

this.createEmptyMovieClip("myMC",1);

mySound = new Sound(myMC);

mySound.attachSound("music_" + Math.floor(Math.random() * 4 + 1));

mySound.start(0,1);

But can't figure out how to do it in ActionScript 3.

This topic has been closed for replies.
Correct answer kglad

try:

var C:Class=Class(getDefinitionByName("music_"+(1+Math.floor(4*Math.random()))));

var mySound=new C();

mySound.play()

2 replies

HommerAuthor
Participating Frequently
October 23, 2018

Beautiful! Thank you very much!

kglad
Community Expert
Community Expert
October 23, 2018

you're welcome.

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
October 22, 2018

try:

var C:Class=Class(getDefinitionByName("music_"+(1+Math.floor(4*Math.random()))));

var mySound=new C();

mySound.play()