Sunday, April 6, 2008

Play mp3 files in AS3

Here is a method that can be called to play a an MP3 file. If there is a current file playing it stops before starting the next one. It should be noted that once you call the play() method on a Sound you cannot load another mp3 into it -- you need to create a new one.

I should probably turn this into a class to make it easier for reuse:

import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;

private var _soundChannel:SoundChannel;
private var _sound:Sound;

soundVolume = new SoundTransform();
soundVolume.volume = 1;

public function getVolume():SoundTransform{
return soundVolume;
}

public function playSound(url:String):void{
var request:URLRequest = new URLRequest(url);
if(_soundChannel!=null){
_soundChannel.stop();
_sound = null;
}
_sound = new Sound();
_sound.load(request);
_soundChannel = _sound.play();
_soundChannel.soundTransform = getVolume();
}

playSound("myfile.mp3");

No comments: