package { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.net.URLRequest; import flash.net.URLStream; import flash.utils.ByteArray; import mx.controls.Alert; import mx.events.CloseEvent; [Event(name="progress",type="flash.events.ProgressEvent")] [Event(name="bufferReady",type="flash.events.Event")] public class VideoDownloader extends EventDispatcher { public static const BUFFER_READY:String = "bufferReady"; [Bindable] private var urlStream:URLStream; private var fileData:ByteArray; private var fileStream:FileStream; private var file:File; private var urlVideo:String; private var saveTo:String; private var bufferDownloaded:Boolean = false; public var defaultBufferSize:uint; public function VideoDownloader(_urlVideo:String,_saveTo:String,_defaultBufferSize:uint=500000):void{ urlVideo = _urlVideo; saveTo = _saveTo; defaultBufferSize = _defaultBufferSize; } public function downloadAndPlay():void{ file = File.documentsDirectory.resolvePath(saveTo); if(file.exists){ Alert.show("File '"+saveTo+"' exists, rewrite?","File",Alert.YES|Alert.CANCEL,null,openFileCloseHandler); return; } openFileForWrite(); startDownloadStream(); } public function getSize():Number{ var _file:File = File.documentsDirectory.resolvePath(saveTo); return _file.size; } public function getDiskLocation():String{ return File.documentsDirectory.url+'/'+saveTo; } public function stopDownload():void{ urlStream.close(); fileStream.close(); } private function startDownloadStream():void{ trace("startDownloadStream"); var req:URLRequest = new URLRequest(urlVideo); urlStream = new URLStream(); urlStream.addEventListener(ProgressEvent.PROGRESS, writeFile); urlStream.addEventListener(Event.COMPLETE,function(event:Event):void{fileStream.close();}); urlStream.addEventListener(IOErrorEvent.IO_ERROR,ioError); urlStream.load(req); bufferDownloaded = false; } private function openFileCloseHandler(event:CloseEvent):void{ if(event.detail==Alert.YES){ openFileForWrite(); startDownloadStream(); } } private function openFileForWrite():void{ fileStream = new FileStream(); // WRITE = create new file fileStream.open(file, FileMode.WRITE); } private function writeFile(event:ProgressEvent):void { dispatchEvent(event); // chunk of new data var fileDataChunk:ByteArray = new ByteArray(); // read bytes from the internet using URLStream urlStream.readBytes(fileDataChunk,0,urlStream.bytesAvailable); // write bytes to the disk using FileStream fileStream.writeBytes(fileDataChunk,0,fileDataChunk.length); // buffering if(bufferDownloaded==false){ if(event.bytesLoaded>defaultBufferSize){ bufferDownloaded=true; dispatchEvent(new Event("bufferReady")); } } } private function ioError(event:IOErrorEvent):void{ Alert.show("ioError: "+event.text); } } }