sound.totalBytes ?

by Thy
hum.. ^^'
CAREFUL: this may #fail your flash pluggin.
♥2 | Line 350 | Modified 2010-10-27 09:10:14 | MIT License
play

ActionScript3 source code

/**
 * Copyright Thy ( http://wonderfl.net/user/Thy )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/3M8n
 */

package 
{
    import flash.display.Graphics;import flash.display.Sprite;import flash.events.Event;
     //[SWF(backgroundColor = 0xFF0000)]   
    /*** @author Thi*/
    public class Main extends Sprite 
    { public function Main():void {
            var p:Player = new Player();
            p.push("http://thethi.webs.com/m/39%20Glee%20Cast%20-%20It's%20My%20Life-Confessions%20Pt.II.mp3", "It's My Life-Confessions Pt.II")
            p.push("http://aolradio.podcast.aol.com/aolmusic/mp3s/Nirvana_AboutAGirl.mp3", "About A Girl")
            p.push("http://phoenix.vlcteam.free.fr/Son/Bourrier/02 - Helicopter.mp3", "Helicopter")
            p.push("http://thymusic.webs.com/m/13%20David%20Guetta%20&%20Chris%20Willis%20Feat%20Fergie%20&%20Lmfao%20-%20Gettin%20Over%20You.mp3", "Gettin Over You")
            p.init(stage);
            
            var _play:Sprite = new Sprite() // play graph (square)
            var g:Graphics = _play.graphics;
            g.beginFill(0);    g.drawRect(10, 10, 10, 10)
            this.addChild(_play);
            
            g = this.graphics; // background
            g.beginFill(0xFF0000)
            g.drawRect(0,0,465,465);
            
            p.player(_play); // play listener
}   }   }

//package 
//{
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.ProgressEvent;
    import flash.events.SampleDataEvent;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.media.SoundTransform;
    import flash.net.URLRequest;
    import flash.system.Security;
    import flash.utils.ByteArray;
    import flash.display.Stage
    
    
    /**
     * ...
     * @author Thi
     * 
     * Playe v 0.9
     * English version.
     * 
     * 
     * var       : Type = function
     * 
     * track     : int = track ID that is playing (0 = first).
     * loading   : Num = loading relation (0 = 0%) (1 = 100%).
     * playing   : Num = playing relation (0 = 0%) (1 = 100%).
     * length    : Num = music length (miliseconds) that is playing.
     * string    : Str = music name that is playing.
     * listening : Boo = if user wants to listen.
     * active    : Boo = if buttons are activated.
     * 
     * 
     * method (..param : Type) = function
     * 
     * init   (st : Stage)     = use 'init(this)' from the stage. It activates the class. 
     *                           Still, it needs an mouseMove to really start (automatic).
     * change (_track : int)   = request new music. _track is the ID (0 = first).
     * pause  ()               = save the position & stop the music that is playing.
     * stop   ()               = reset the position & stop the music that is playing.
     * play   ()               = play the music.
     * volume (volume: Num)    = change music volume. must send volume number (0 = 0%) (1 = 100%).
     * 
     * to add music to the playlist, u call:
     * push (url : str, name : str, artist : str) = add an new music at the end of the list.
     *                                              url is the stream downloadable link.
     *                                              name can be the music's name.
     *                                              artist can be the artist's name.
     * 
     * 
     * TODO:
     * - SoundSpectrum feature.
     * - Youtube music option.
     * 
     * 
     * @mail thy@hotmail.com.br
     * @web http://wonderfl.net/user/Thy
     */
    /*public*/ class Player extends Sprite 
    {
        public var // global var
        st:Stage; // stage
        
        public var 
        musics:Array = [], // Music list
        track:int, // 'now playing', as musics index
        loading:Number = 0,
        playing:Number = 0,
        length:Number = 0,
        string:String = "",
        listening:Boolean,
        active:Boolean; // if player is active
        
        private var // Sound related
        sound:Sound = new Sound(),
        channel:SoundChannel = new SoundChannel(),
        transf:SoundTransform = new SoundTransform(),
        loaded:Boolean,
        position:Number = 0,
        playing_old:Number,
        reset:int = 40;
        
        private var // Sound extract
        sound_ext:Sound = new Sound(),
        ext:ByteArray = new ByteArray(),
        ext_pos:int = -1,
        zero_byte:ByteArray = new ByteArray();
        
        private var
        request:URLRequest = new URLRequest();
        
        
        public function init( st:Stage = null ):void
        {
            inittrace(st);
            trace("Question 1: Why sound.totalBytes are")
            trace("not the REAL total bytes?")
            trace("I added a couple of music in there,")
            trace("i didnt put any credit cuz u cant even")
            trace("heard it, an its for testing")
            trace("")
            trace("Question 2: does it bug in your")
            trace("computer? sort off.. after a 'random' while,")
            trace("my flash #fail.")
            trace("")
            trace("PS. the music play fast, to see the")
            trace("totalBytes thing fast.")
            trace("")
            trace("PS2. this is about streaming extract ^^")
            trace("")
            trace("plz im rlly confused!")
            trace("thx alot ^^'")
            trace("")
            trace("")
            
            //Security.LOCAL_TRUSTED;
            trace("player: initialize (by developer)");
            this.st = st;
            channel.soundTransform = transf;
            st.addEventListener(MouseEvent.MOUSE_MOVE, canStart);
        }
        
        private function canStart(e:MouseEvent):void 
        {
            trace("player: initialize (by user, mouse moved)");
            st.removeEventListener(MouseEvent.MOUSE_MOVE, canStart);
            sound_ext.addEventListener(SampleDataEvent.SAMPLE_DATA, sample);
            st = null;
            track = 0;
            ext_pos = -1;
            var j:int = -1;
            while (++j < 8192)
            {
                zero_byte.writeFloat(0);
            }
            
            load();
        }
        
        private function sample(e:* /*SampleDataEvent*/):void 
        {
            var num:uint;
            if (loaded)
            {
                num = sound.bytesTotal 
            } else
            {
                num = sound.bytesLoaded;
            }
            if (num > ext_pos + uint(4096))
            {
                ext.clear()
                ext_pos += Sound(sound).extract(ext, 4096, ext_pos);
                ext_pos += 8192 * 8 // just to go fast ^^'
                e.data.writeBytes(ext);
            } else
            {
                if (loaded)
                {
                    ext.clear()
                    num = Sound(sound).extract(ext, 4096, ext_pos);
                    ext_pos += num;
                    ext_pos += 8192 * 11 // just to go fast ^^'
                    e.data.writeBytes(ext);
                    if (num == 0)
                    {
                        trace("~")
                        trace("sound.bytesTotal:", sound.bytesTotal)
                        trace("THE REAL SIZE:", ext_pos - 8192 * 10)
                        trace("~")
                        trace("player: End of music. requesting next..")
                        change(++track);
                    } else
                    {
                        //trace("acabo nada.. num =", num);
                    }
                    return;
                }
                //trace(":(")
                e.data.writeBytes(zero_byte);
            }
            
        }
        
        
        public function change(_track:int = 0):void
        {
            trace("player: music change request");
            if (!active) return;
            active = false;
            this.track = _track;
            if (track > musics.length-1) track = 0;
            if (track < 0) track = musics.length - 1;
            trace("player: track ID =",track)
            
            // trash
            if (!loaded) sound.close();
            loaded = false;
            position = 0;
            ext_pos = -1;
            reset = 40;
            channel.stop();
            
            // load
            load();
        }
        
        private function load():void
        {
            trace("player: loading the music..");
            // load setup & string
            var music:Music;
            
            music = musics[track];
            request.url = music.url;
            sound = new Sound();
            sound.load(request);
            string = music.name + " " + music.artist;
            trace("player: artist name =", string)
            
            // loading music
            sound.addEventListener(Event.COMPLETE, loadComplete);
            sound.addEventListener(ProgressEvent.PROGRESS, loadProgress);
            this.addEventListener(Event.ENTER_FRAME, ef);
            
            
            if (listening) 
            {
                channel = sound_ext.play();
                trace("player: playing the music..");
            }
            active = true;
        }
        
        
        private function loadComplete(e:Event):void 
        {
            trace("player: music loading complete!");
            sound.removeEventListener(Event.COMPLETE, loadComplete);
            sound.removeEventListener(ProgressEvent.PROGRESS, loadProgress);
            trace("(event) load complete, sound.bytesTotal:",sound.bytesTotal)
            
            loaded = true;
            loading = 1;
            length = sound.length;
        }
        
        private function loadProgress(e:ProgressEvent):void 
        {
            loading = e.bytesLoaded / e.bytesTotal;
            length = sound.length / loading;
        }
        
        private function ef(e:Event):void 
        {
            if (listening && false)
            {
                playing = channel.position / length;
                if (playing_old >= playing)
                {
                    trace("player: may reset music..", reset);
                    if (--reset == 0)
                    {
                        trace("player: reset!");
                        reset = 40;
                        stop();
                        play();
                        return;
                    }
                }
                playing_old = playing;
                if (playing >= .99 && playing != Infinity) change(++track);
            }
        }
        
        
        public function pause():void
        {
            trace("player: pause request");
            if (!active) return;
            if (listening)
            {
                listening = false;
                position = channel.position;
                channel.stop();
            }
        }
        
        public function stop():void
        {
            trace("player: stop request");
            if (!active) return;
            position = 0;
            ext_pos = -1;
            if (listening)
            {
                listening = false;
                channel.stop();
            }
        }
        
        public function play():void
        {
            trace("player: play request");
            if (!active) return;
            if (!listening)
            {
                listening = true;
                /*channel = */sound_ext.play();
                //channel = sound.play(position);
                //channel = sound.play(position);
                trace("player: playing the music..");
            }
        }
        
        public function volume(volume:Number = 1):void
        {
            trace("player: volume request");
            if (!active) return;
            if (transf.volume != volume)
            {
                transf.volume = volume;
                channel.soundTransform = transf;
            }
        }
        
        
        public function player(s:Sprite = null):void
        {
            s.addEventListener(MouseEvent.CLICK, function():void { play() } );
        }
        public function stoper(s:Sprite = null):void
        {
            s.addEventListener(MouseEvent.CLICK, function():void { stop() } );
        }
        public function nexter(s:Sprite = null):void
        {
            s.addEventListener(MouseEvent.CLICK, function():void { change(track +1) } );
        }
        public function prever(s:Sprite = null):void
        {
            s.addEventListener(MouseEvent.CLICK, function():void { change(track -1) } );
        }
        public function pauser(s:Sprite = null):void
        {
            s.addEventListener(MouseEvent.CLICK, function():void { pause() } );
        }
        
        
        public function push(url:String = "", name:String = "", artist:String = ""):void
        {
            musics.push(new Music(url, name, artist));
        }
    }
    
//}

class Music
{
    public var
    url:String,    name:String, artist:String;
    
    public function Music(url:String = "", name:String = "", artist:String = ""):void
    {
        this.url = url; this.name = name; this.artist = artist;
    }
}

// forked from http://wonderfl.net/c/4efk
// http://wonderfl.net/user/seikimaiii
////  WONDERFL TRACE /////

import flash.display.Sprite;
import flash.display.Stage;
import flash.text.TextField;
import flash.text.TextFormat;


function inittrace(s:Stage):void
{
    WTrace.initTrace(s);
}

//global trace function
var trace:Function;

//wtreace class
class WTrace
{
        private static var FONT:String = "Fixedsys";
        private static var SIZE:Number = 12;
        private static var TextFields:Array = [];
        private static var trace_stage:Stage;
        
        public static function initTrace(stg:Stage):void
        {
            trace_stage = stg;
            trace = wtrace;
        }
        
        private static function scrollup():void
        {
            // maximum number of lines: 100
            if (TextFields.length > 40) 
            {
                var removeme:TextField = TextFields.shift();
                trace_stage.removeChild(removeme);
                removeme = null;
            }
            for(var x:Number=0;x<TextFields.length;x++)
            {
                (TextFields[x] as TextField).y -= SIZE*1.2;
            }
        }
    
        public static function wtrace(... args):void
        {
        
            var s:String="";
            var tracefield:TextField;
            
            for (var i:int;i < args.length;i++)
            {
                // imitating flash:
                // putting a space between the parameters
                if (i != 0) s+=" ";
                s+=args[i].toString();
            }
            

            tracefield= new TextField();
            tracefield.autoSize = "left";
            tracefield.text = s;
            tracefield.y = trace_stage.stageHeight - 20;
            tracefield.width = trace_stage.stageWidth;

            var tf:TextFormat = new TextFormat(FONT, SIZE, 0xFFFFFF);
            tracefield.setTextFormat(tf);
            trace_stage.addChild(tracefield);
            scrollup();                      
            TextFields.push(tracefield);
            
        }
}

Forked