This is the entirety of loading an audio file, set up for use in a class.

Can be used to play an MP3 or any other acceptable audio format.

Usage:

loadAudio(“someSubDirectory/filename”, {Boolean});

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

// This audioRootDir is a local file, but can be any URL that the Flash Player has access to.
private var audioRootDir:String = "file:///drive:/folder/";

private var hasAudio:Boolean;
private var audioChannel:SoundChannel;
private var sndStream:URLRequest;
private var audio:Sound;


public function loadAudio(audioFile:String = "", loopAudio:Boolean = true):void
		{
			try 
			{
				if (audioFile !== "") 
				{
					// setup file and sound
					sndStream = new URLRequest(audioRootDir + audioFile);
					audio = new Sound();
					audio.addEventListener(IOErrorEvent.IO_ERROR, audioLoadErrorHandler, false, 0, true);

					//use this for events to run when audio is fully loaded: 
					// audio.addEventListener(Event.COMPLETE, audioLoadedHandler, false, 0, true);
					
					// load the audio file
					audio.load(sndStream);
					
					// Set to loop 1000 times, which avoids the need to add a listener for Event.SOUND_COMPLETE events;
					// if there is a need for perpetual looping, however, use the event (not shown here).
					// Start audio 
					// and loop the audio, if required.
					audioChannel= audio.play(0, (loopAudio ? 1000 : 0));					
					
					hasAudio = true;
				}
				else 
				{
					hasAudio = false;
				}
			}
			catch (err:Error)
			{
				hasAudio = false;
				trace("Error: loadAudio: err msg: " + err + "\n" + err.getStackTrace() );
			}
			finally { }
		}
		
		private function audioLoadErrorHandler(e:IOErrorEvent):void 
		{
			trace("Error: audioLoadErrorHandler: err msg: " + e + "\n" + e.toString());
		}

– 30 –

Advertisements