loading files to externally hosted swf actionscript 3 - actionscript-3

I have created a music playing flash, it works great and all when I'm running it from my local storage i.e (opening the swf directly from my computer)
but when I open the swf from a server it doesn't load the file. I've added the input handler below.
function addTrack(){
var trackChecker: URLLoader = new URLLoader();
if (String(path.text).substr(-4, 4) == ".mp3") {
txtError.text = "";
trackChecker.load(new URLRequest(String(path.text)))
} else {
if (String(path.text).substr(-4, 1) == ".") {
txtError.text = "Wrong format, tried to open " + String(path.text).substr(-4, 4) + ", but the only currently supported format is .mp3";
} else {
path.appendText(".mp3");
txtError.text = "";
trackChecker.load(new URLRequest(String(path.text)))
}
}
trackChecker.addEventListener(Event.COMPLETE, addToList);
trackChecker.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
}
function onIOError(e: IOErrorEvent) {
txtError.text = "No file found or file is damaged";
}
function addToList(e: Event) {
addedTrack = true;
tempSong = new Sound();
tempSong.load(new URLRequest(String(path.text)));
tempSong.addEventListener(Event.COMPLETE, tempData);
ActualArray[ActualArray.length] = ["Placeholder", "Placeholder", "Placeholder", "Placeholder", String(path.text)];
}
function tempData(e: Event) {
var tempTrackName;
var tempName: Array = tempSong.url.split("/");
if (String(tempSong.id3.songName) == "null") {
tempTrackName = String(tempName[tempName.length - 1].replace(".mp3", ""));
} else {
tempTrackName = (String(tempSong.id3.songName));
}
path.text = "";
for (var i: int = 3; i < tA.length - 1; i++) {
path.appendText(tempName[i]);
path.appendText("\\");
}
addToGrid(int(ActualArray.length - 1), tempSong.length, tempTrackName);
path.setSelection(path.text.length, path.text.length);
}
Worth noting that the script stops before it can change path.text, i.e. in the middle of "function tempData(e: Event)" or earlier. in stop i mean nothing happens, the other scripts work, but when you try to add a track nothing happens at all. but I can't recreate the glitch on my computer, because it only exists when the swf is hosted externally.

Related

Dynamically add all Segment files to a manifest in JavaScript

I am trying to create and play a playlist manifest using HLS. I am looping over all the segment files to add their names to the file/provide their url, but when I run my function, I get the error below, which means it's not properly receiving the urls:
[error] > 0 while loading data:application/x-mpegURL;base64,undefined
Here's my code:
segment_files = ["https://gib.s3.amazonaws.com/segment/first.ts", "https://gib.s3.amazonaws.com/segment/2nd.ts", "https://gib.s3.amazonaws.com/segment/first.ts"
function create_manifest() {
if (hls == undefined) {
player = document.createElement("video");
document.body.appendChild(player);
player.pause();
player.src = "";
for (let ii = 0; ii < segment_files.length; i++) {
var segment = segment_files[ii];
}
var manifestfile = btoa(
`#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-PLAYLIST-TYPE:VOD\n#EXT-X-TARGETDURATION:11\n#EXTINF:10.000,\n${segment}\n#EXT-X-ENDLIST`
);
}
if (Hls.isSupported()) {
hls = new Hls({
debug: true,
enableWorker: true,
lowLatencyMode: true,
});
hls.attachMedia(player);
hls.loadSource("data:application/x-mpegURL;base64," + manifestfile);
player.muted = true;
player.play();
}
}

Why is FileReferenceList.fileList type NULL on MAC OS

I have an application that uploads files to a server. In the onSelectFile function, I check the file type to see if it is valid. I also have a FileFilter that limits what the user can select, but I wanted to double check that they are uploading a correct file type.
On a PC, I can get the value of type for the file, but on a Mac (Safari, Firefox, Chrome), I get NULL.
Here is the function where I try to get the type
// Called when a file is selected
private function onSelectFile(event:Event):void {
//let's see if we're dealing with a new album or an existing album
var arrFoundList:Array = new Array();
// Get list of files from fileList, make list of files already on upload list
for (var i:Number = 0; i < _arrUploadFiles.length; i++) {
for (var j:Number = 0; j < _refAddFiles.fileList.length; j++) {
if (_arrUploadFiles[i].name == _refAddFiles.fileList[j].name) {
arrFoundList.push(_refAddFiles.fileList[j].name);
_refAddFiles.fileList.splice(j, 1);
j--;
}
}
}
if (_refAddFiles.fileList.length >= 1) {
for (var k:Number = 0; k < _refAddFiles.fileList.length; k++) {
var fileType:String = _refAddFiles.fileList[k].type;
Alert.show("File type: " + fileType.toString() + " | name: " + _refAddFiles.fileList[k].name); //fileType is always NULL on Mac
var validTypes:Array = new Array(".jpg", ".jpeg", ".gif", ".png", ".JPG", ".JPEG", ".GIF", ".PNG");
if (validTypes.indexOf(fileType.toLowerCase()) < 0)
{
Alert.show("The file type: " + fileType + " is not valid (file: " + _refAddFiles.fileList[k].name + "). Valid types are .jpg, .gif, and .png", "Invalid File Type");
continue;
}
//start the upload for each file
var item:OneFile= new OneFile();
item.fileName=_refAddFiles.fileList[k].name;
item.fileSize=_refAddFiles.fileList[k].size;
item.file=_refAddFiles.fileList[k];
_bytesTotal+=_refAddFiles.fileList[k].size;
if (existingalbum.selected)
{
item.album=albums.selectedItem.#aid;
}
fileList.addChild(item);
_files.addItem(item);
_numFiles++;
}
startUpload();
}
else
{
Alert.show("No files were added to the list to be uploaded.");
}
if (arrFoundList.length >= 1) {
Alert.show("The file(s): \n\n• " + arrFoundList.join("\n• ") + "\n\n...are already on the upload list. Please change the filename(s) or pick a different file.", "File(s) already on list");
}
else{ // some comment
}
}
Here is a work-around that I found:
public static function extractFileType(fileName:String):String {
var extensionIndex:Number = fileName.lastIndexOf(".");
if (extensionIndex == -1) {
return "";
} else {
return "." + fileName.substr(extensionIndex + 1,fileName.length);
}
}
http://www.josh-ho.com/as3-mac-filereference-type-workaround/

How to get byteArray or base64 string from RenderTexture Cocos2d-JS

I am making a game on cocos2d-JS for facebook in which there is a requirement of sharing a screenshot of the game.
I am able to take the screenshot but now I am unable to upload it in the Parse.com server because it requires base64 format or byte array. I am unable to find any solution of converting Sprite in to this format.. Here's my code so result when I do addchild its coming proper .. I have also added my commented code so that it will help to understand that I have tried lot of things but couldnt achieve the same.
shareToSocialNetworking: function () {
cc.director.setNextDeltaTimeZero(true);
var newsize = cc.director.getVisibleSize();
var renderText = new cc.RenderTexture(newsize.width,newsize.height);
renderText.begin();
cc.director.getRunningScene().visit();
renderText.end();
var result = cc.Sprite.create(renderText.getSprite().getTexture());
result.flippedY = true;
this._mainViewNode.addChild(result,6000);
//renderText.saveToFile("screenshot.jpg",cc.IMAGE_FORMAT_PNG);
//var based = renderText.getSprite().getTexture().getStringForFormat().toString();
//var data = based.getData();
var file = new Parse.File("screen.jpg", { base64: this.getBase64(result) });
//var file = new Parse.File("screen.jpg", data, "image/png");
var self = this;
file.save().then(function() {
// The file has been saved to Parse.
alert(file.url);
this.onSharePictureInfoLink(file.url());
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
//
//var ccImage = renderText.newCCImage();
//
//var str = ccImage.getData();
},
is there any workaround that can be done
there is a private variable called _cacheCanvas, which is the instance of the offscreen canvas
you can simply do renderText._cacheCanvas.toDataURL()
Here's how you can take the screnshot from cocos2d-JS
screenshot: function (fileName) {
var tex = new cc.RenderTexture(winSize.width, winSize.height, cc.Texture2D.PIXEL_FORMAT_RGBA8888);
tex.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
tex.begin();
cc.director.getRunningScene().visit();
tex.end();
var imgPath = jsb.fileUtils.getWritablePath();
if (imgPath.length == 0) {
return;
}
var result = tex.saveToFile(fileName, cc.IMAGE_FORMAT_JPEG);
if (result) {
imgPath += fileName;
cc.log("save image:" + imgPath);
return imgPath;
}
return "";
}
then make a Java call from Javascript
public static void ScreenShot()
{
Bitmap imageBitmap = BitmapFactory.decodeFile(Cocos2dxHelper.getCocos2dxWritablePath() + "/" + "screenshot.png");
String fileHolder = "SampleFolder";
File filepathData = new File("/sdcard/" + fileHolder);
//~~~Create Dir
try {
if (!filepathData.exists())
{
filepathData.mkdirs();
filepathData.createNewFile();
FileWriter fw = new FileWriter(filepathData + fileHolder);
BufferedWriter out = new BufferedWriter(fw);
String toSave = String.valueOf(0);
out.write(toSave);
out.close();
}
}
catch (IOException e1) {
}
//~~~Create Image
File file = new File("/sdcard/" + "Your filename");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
imageBitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e) {}
Uri phototUri = Uri.fromFile(file);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
//~~~Add Code Below
}
Do not forget to add permission for external storage

How to Read a text file using Java script and display it in column fashion in HTML.?

This is the code which reads the text file using the Jscript and displays it in HTML. But i need it to display it in table.
How to display it in Table.
< this is my first question so i hope i get solution >
`
Read File (via User Input selection)
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>`
Please help me in this
You could format the text file like a SSV (TSV or CSV as well), then instead of ReadAll() I'd do something like this:
var file = reader.OpenTextFile(filePath, 1),
data = [], n;
while (!file.AtEndOfStream) {
data.push(file.ReadLine().split(';')); // or use some other "cell-separator"
}
Then the rest is a lot simpler and faster, if you've an empty table element in your HTML:
<table id="table"></table>
Now just create rows and cells dynamically based on the data array:
var table = document.getElementById('table'),
len = data.length,
r, row, c, cell;
for (r = 0; r < len; r++) {
row = table.insertRow(-1);
for (c = 0; c < data[r].lenght; r++) {
cell.row.insertCell(-1);
cell.innerHTML = data[r][c];
}
}

Problems loading XML file (url cannot load) on local machine

I'm trying to have my flash application interpret an XML file. My code looks like:
function onFinish(success_boolean, results_obj, xml)
{
if (success_boolean)
{
play ();
} // end if
} // End of the function
Stage.align = "MC";
Stage.scaleMode = "noScale";
url = "25358";
_root.cacheKiller = "true";
stop ();
var parsed_obj = {};
var unCash = new Date().getTime();
if (_root.cacheKiller == "true")
{
fileToLoad = url + "_main.xml?cacheKiller=" + unCash;
fileToLoad = url + "_main.xml";
}
else
{
fileToLoad = url + "_main.xml";
} // end else if
gs.dataTransfer.XMLParser.load(fileToLoad, onFinish, parsed_obj);
_root.emp.useHandCursor = 0;
_root.mus = 1;
_root.n = 1;
_root.num = 1;
the output i get is:
Error opening URL 'file:///C|/try/25358undefined'
Does anyone have any idea why i can't access this file? I've verified that the URL works.
You have a wrong url. I mean that fileToLoad contains a wrong value. Try to trace this variable.