In two week ago I have some case, I have to create an Multimedia Application Presentation in Flash with ActionScript 3. In my project, I need to play some background music which are have to play automatically and random at the start up from external mp3 files, rather then play the same song at first all the time.

In this post I want to share what I got. The code are simple, to implement only need to create new folder for music files in project folder, naming the files by sequentially. so you can use the code for your projects.

In this case, I have 6 .mp3 files in folder "musics", I named the mp3 files sequels (music1.mp3, … ,music6.mp3).

Here are the Actionscript :

import flash.media.Sound; 
import flash.net.URLRequest; 
import flash.media.SoundChannel; 
import flash.events.Event;

playsong(); 
//var songs:Array=new Array("music1.mp3","music2.mp3","music3.mp3","music4.mp3"); 
var sound:Sound; 
var soundChannel:SoundChannel; 
var randnum:uint; 
function playsong() 
{ 
randnum=Math.floor(Math.random()*6); 
sound=new Sound(); 
var songs:String= "music" + randnum + ".mp3"; 
sound.load(new URLRequest("musics/"+songs)); 
soundChannel=sound.play(); 
soundChannel.addEventListener(Event.SOUND_COMPLETE,playrandomsong); 
} 
function playrandomsong(e:Event) 
{ 
playsong(); 
}

The notes:

  • in line 13 change the number of 6 with the total number of the music files you have.
  • if you have your music files in different name or if you like to list the files inside the code, remove the comment mark in line 7, remove line 15 and then replace line 16 with this code.
sound.load(new URLRequest("musics/"+musics[randnum]));