For one of my projects I encountered an issue where I was unable to retrieve how long my sound object was. I needed to know how long the song that was loaded was in order to display a playing progress bar. I found out that because of the way I was instantiating my variables, this was causing an issue with the sound object. Here is a bit of code to exemplify finding the length of a externally loaded .mp3 file:
package
{
import flash.display.Sprite;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.Event;
public class MP3Player extends Sprite
{
private var s:Sound;
private var channel:SoundChannel;
private var loadTime:Number;
private var loadPercent:uint;
private var playLoadTime:Number;
private var playbackPercent:uint;
private var output:TextField;
public function MP3Player()
{
Output();
playSong();
}
public function playSong():void
{
// create a new sound
s = new Sound();
// load the mp3
s.load(new URLRequest("/path/to/mp3/file/*.mp3"));
// play the music
channel = s.play();
addEventListener(Event.ENTER_FRAME, SoundPlayingHandler);
}
private function SoundPlayingHandler(e:Event):void
{
var totalBytes = s.bytesTotal;
loadTime = s.bytesLoaded / totalBytes;
loadPercent = Math.round(loadTime * 100);
var playLoadTime:Number = s.bytesLoaded / s.bytesTotal;
var estimatedLength:int = Math.ceil(s.length / (playLoadTime));
var playbackPercent:uint = Math.round(100 * (channel.position / estimatedLength));
output.text = "Length of Song: " + (Math.round(((estimatedLength / 1000) / 60) * 100) / 100) + "\nPlaying " + playbackPercent + "%\nLoading " + loadPercent + "%";
}
// UI elements
public function Output():void
{
// Small Black Text Formatting
var smallBlackFormat:TextFormat = new TextFormat();
smallBlackFormat.font = "Arial";
smallBlackFormat.color = 0x000000;
smallBlackFormat.size = 10;
smallBlackFormat.underline = false;
// output TextField
output = new TextField();
output.defaultTextFormat = smallBlackFormat;
addChild(output);
output.width = 700;
output.height = 200;
output.x = 0;
output.y = 0;
output.multiline = true;
output.wordWrap = true;
output.border = true;
output.background = true;
output.text = "DEBUGGING:\n";
}
}
}
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.