how to find URL of the page where the Flash file is embedded - html

I am writing a Flash app in Flex Builder 3.
I have a problem. I need the URL of the place where the Flash app has been embedded.
mx.core.Application.application.url
This gives me the address of the original swf file, but I actually need the URL of the HTML file where this SWF has been embedded.
is there a way ???
thanks!
Ali

You have 2 options.
in flex:
private function initApp():void {
browserManager = BrowserManager.getInstance();
browserManager.addEventListener(BrowserChangeEvent.URL_CHANGE, showURLDetails);
browserManager.init("", "Welcome!");
}
and the listener
private function showURLDetails(e:BrowserChangeEvent):void {
var url:String = browserManager.url;
baseURL = browserManager.base;
fragment = browserManager.fragment;
previousURL = e.lastURL;
fullURL = mx.utils.URLUtil.getFullURL(url, url);
port = mx.utils.URLUtil.getPort(url);
protocol = mx.utils.URLUtil.getProtocol(url);
serverName = mx.utils.URLUtil.getServerName(url);
isSecure = mx.utils.URLUtil.isHttpsURL(url);
}
That code works both on the server and on Local host.
if that does not work for you (upload the error here first) but you can also create a JS function that will return the URL and have flex call this function.

my comment is unreadable so here it is as an answer.
The code inside SWFObject makes flash act alittle wacky when it comes to the browser manager.
the solution is inside history.js (first attach it to the HTML if you didn't)
Then, comment out these lines of code.
if (players.length == 0 || players[0].object == null) {
var tmp = document.getElementsByTagName(‘embed’);
players = tmp;
}
And this one
if (player == null || player.object == null) {
 player = document.getElementsByTagName(‘embed’)[0];
 }
This should solve your problem.

Related

HTML5 audio seek is not working properly. Throws Response Content-Length mismatch Exception

I'm trying to stream audio file to Angular application where is html5 audio element and src set to my api end point (example. /audio/234). My backend is implemented with .NET Core 2.0. I have implemented already this kind of streaming: .NET Core| MVC pass audio file to html5 player. Enable seeking
Seek works if I don't seek to end of file immediately when audio starts playing. I use audio element's autoplay attribute to start playing immediately audio element has enough data. So in my situation audio element has not yet all the data when I seek so it make new GET to my API. In that situation in my backend log there is this Exception:
fail: Microsoft.AspNetCore.Server.Kestrel[13]
[1] Connection id "0HL9V370HAF39", Request id "0HL9V370HAF39:00000001": An unhandled exception was thrown by the application.
[1] System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 6126919).
Here is my audio controller GET method.
byte[] audioArray = new byte[0];
//Here I load audio file from cloud
long fSize = audioArray.Length;
long startbyte = 0;
long endbyte = fSize - 1;
int statusCode = 200;
var rangeRequest = Request.Headers["Range"].ToString();
_logger.LogWarning(rangeRequest);
if (rangeRequest != "")
{
string[] range = Request.Headers["Range"].ToString().Split(new char[] { '=', '-' });
startbyte = Convert.ToInt64(range[1]);
if (range.Length > 2 && range[2] != "") endbyte = Convert.ToInt64(range[2]);
if (startbyte != 0 || endbyte != fSize - 1 || range.Length > 2 && range[2] == "")
{ statusCode = 206; }
}
_logger.LogWarning(startbyte.ToString());
long desSize = endbyte - startbyte + 1;
_logger.LogWarning(desSize.ToString());
_logger.LogWarning(fSize.ToString());
Response.StatusCode = statusCode;
Response.ContentType = "audio/mp3";
Response.Headers.Add("Content-Accept", Response.ContentType);
Response.Headers.Add("Content-Length", desSize.ToString());
Response.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", startbyte, endbyte, fSize));
Response.Headers.Add("Accept-Ranges", "bytes");
Response.Headers.Remove("Cache-Control");
var stream = new MemoryStream(audioArray, (int)startbyte, (int)desSize);
return new FileStreamResult(stream, Response.ContentType)
{
FileDownloadName = track.Name
};
Am I missing some Header or what?
I didn't get this exception with .NET Core 1.1 but I'm not sure is it just coincident and/or bad testing. But if anybody has information is there something changed in .NET Core related to streaming I will appreciate that info.
Now when I research more I found this: https://learn.microsoft.com/en-us/aspnet/core/aspnetcore-2.0 look Enhanced HTTP header support- heading. It says this
If an application visitor requests content with a Range Request header, ASP.NET will recognize that and handle that header. If the requested content can be partially delivered, ASP.NET will appropriately skip and return just the requested set of bytes. You do not need to write any special handlers into your methods to adapt or handle this feature; it is automatically handled for you.
So all I need is some clean up when I move to .NET Core 1.1 to 2.0 because there is already handler for those headers.
byte[] audioArray = new byte[0];
//Here I get my MP3 file from cloud
var stream = new MemoryStream(audioArray);
return new FileStreamResult(stream, "audio/mp3")
{
FileDownloadName = track.Name
};
Problem was in Headers. I don't know exactly which header was incorrect or was my stream initialization incorrect but now It's working. I used this https://stackoverflow.com/a/35920244/8081009 . Only change I make this was renamed it as AudioStreamResult. And then I used it like this:
Response.ContentType = "audio/mp3";
Response.Headers.Add("Content-Accept", Response.ContentType);
Response.Headers.Remove("Cache-Control");
var stream = new MemoryStream(audioArray);
return new AudioStreamResult(stream, Response.ContentType)
{
FileDownloadName = track.Name
};
Notice that I pass full stream to AudioStreamResult.
var stream = new MemoryStream(audioArray);

How to play html5 game offline?

I wanted to save some html5 games on the laptop for my little brother to play when he's out of wifi range. I downloaded all the files and changed the paths so that no erros appear.
Now when I open index.html a blank page oppen with a loader gif and nothing else loads. I dont understand why? No errors are thrown. The only error is the one that it cannot find ads (when loadvoyager is called). I tried to comment it, still nothing positively happends.
This is an archive of the game: https://www.dropbox.com/s/5x3dk7w693j3os1/caca.rar?dl=0
Thank you!
Solution
Go to this site:
http://scotty-staging.softgames.de/assets/api/voyager.js
or use this mirror i created:
File only : http://www.mediafire.com/download/4b8uhvm75fbqtwy/voyager.js
Full game: http://www.mediafire.com/download/y8ocia4rr5552jx/html5Game.7z
Save the javascript file in assets and than you can play the game.
update ( problem )
var displayLoadScrn = function(){
var body = SG.d.getElementsByTagName('body')[0];
if( typeof body != "undefined" ){
if( SG.d.getElementById('sg-loadscrn') == null ){
SG.debug && console.log('show load-screen: complete');
body.appendChild(loadScrn);
}
SG.loadVoyager(); //<---- This is where it goes wrong //
}
else{
if(SG.debug) console.log('show load-screen: body-tag not ready. retrying in '+SG.loadScrnTimer+'ms');
setTimeout(displayLoadScrn,SG.loadScrnTimer);
}
};
displayLoadScrn();
var displayImage = function(){
var body = SG.d.getElementsByTagName('body')[0];
if( typeof body != "undefined" ){
body.appendChild(loadScrn);
SG.loadVoyager(); //<---- This is where it also goes wrong //
}
else{
if(SG.debug) console.log('show load-screen: body-tag not ready. retrying in '+SG.loadScrnTimer+'ms');
setTimeout(displayImage,SG.loadScrnTimer);
}
};
displayImage();
The problem is that you didnt provide the voyager resource script in the assets folder, but it needs to be loaded
loadVoyager : function(){
var sgc = document.createElement('script'); sgc.type = 'text/javascript'; sgc.async = true;
var random = Math.floor((Math.random()*100000000)+1);
//sgc.src = 'http://scotty-staging.softgames.de/assets/api/voyager.js';
sgc.src = 'assets/voyager.js?_='+random; //<-- this line //
//sgc.src = '//localhost:3000/assets/api/voyager.js';
sgc.onload = SG.boot;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sgc, s);
},
You see the middle "sgc.src = 'assets/voyager.js?='+random;" , that is still trying to load, what I did is removing the commented out lines, I kept the "sgc.src = 'assets/voyager.js?='+random;" uncommented and downloaded the voyager file and placed it in the assets folder.
You cannot comment out the loadvoyager, because it needs to be loaded. Otherwise your page will be loading all the time, with not response
Looks like a file named voyager.js is missing from the assets folder. Open the console in the browser for this detail(F12 in Chrome).
And just to be on the safer side try opening this game through a local-server this way you don't have to worry about all the things the browser is concerned about when running the game.

Reading a project text file windows phone 8

I'm having trouble accessing a text file that is packaged with my Windows Phone 8 app.
Here is the code:
var ResrouceStream = Application.GetResourceStream(new Uri("Data-Test.docx", UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
// logiic here
retrun "Hi";
}
}
else
{
return "hello";
}
Seems simple but the app always returns "hello". i have placed the file in root and also in assets, changed it to content - copy and do not copy, resource copy and do not copy but always it returns "hello".
Spent several hours on this and all solutions I can find show the solution or very similar above!
What am I doing wrong?
EDIT: Returns "hello" when I deploy to phone or emulator.
also tried "/Data-Test...", #"\Data-Text..., #/"Data-Test...!
UPDATE 1:
string aReturn = "";
var asm = Assembly.GetExecutingAssembly();
//Use this to verify the namespacing of the "Embedded Resource".
//asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var ResourceStream = asm.GetManifestResourceStream("ContosoSocial.Assets.QuizQuestions.QuizQuestions-Test1.docx");
if (ResourceStream != null) // <--CHECKED AND DOES NOT EQUAL NULL
{
Stream myFileStream = ResourceStream;
if (myFileStream.CanRead) // <-- CHEACKED AND CAN READ
{
StreamReader myStreamReader = new StreamReader(myFileStream);
LOGIC & EXCEPTION HERE...?
string myLine = myStreamReader.ReadLine();
}
else
{
aReturn = "myFileStream.CanRead = true";
}
}
else
{
aReturn = "stream equals null";
}
Debug.WriteLine(aReturn);
}
The assignment of myFileStream to a StreamReader object is throwing the exception null pointer. I thought I would wrap myFileStream to a StreamReader so I can read a line at a time..? This is my first c# project and I'm unfamiliar with it's syntax and classes.
UPDATE 2:
OK I added...
Debug.WriteLine(aReturn);
...following...
string myLine = myStreamReader.ReadLine();
...and noticed it was retrieving only the 2 characters 'PK' !
So saved the .docx file as .txt and reinserted adn changed build copy to embedded - do not copy...Happy days it now pulls off the first line in the file.
Thanks to OmegaMan for your help with this one :-)
Change file type in the project to Embedded Resource
Extract the resource by working the namespace to its location. Here is an example code where I pull in an XSD:
Code:
var asm = Assembly.GetExecutingAssembly();
// Use this to verify the namespacing of the "Embedded Resource".
// asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var f1 = asm.GetManifestResourceStream("UnitTests.Resources.NexusResponse.xsd");
Note this is not tested on WP8, but GetExecutingAssembly is stated to work within .Net. If you get the namespace wrong, uncomment out the code and display or debug to determine the resources and their namespace.

Audio API: Fail to resume music and also visualize it. Is there bug in html5-audio?

I have a button. Every time it is clicked, a music is played. When it's clicked the second time, the music resumes. I also want to visualize the music.
So i begin with html5 audio (complete code in http://jsfiddle.net/karenpeng/PAW7r/):
$("#1").click(function(){
audio1.src = '1.mp3';
audio1.controls = true;
audio1.autoplay = true;
audio1.loop = true;
source = context.createMediaElementSource(audio1);
source.connect(analyser);
analyser.connect(context.destination);
});
But when it's clicked more than once, it console.log error:
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
Then i change to use web audio API, and change the source to:
source = context.createBufferSource();
The error is gone.
And then, i need to visualize it.
But ironicly, it only works in html5 audio!
(complete code in http://jsfiddle.net/karenpeng/FvgQF/, it does not work in jsfiddle cuz i dont know how to write processing.js script properly, but it does run on my pc)
var audio = new Audio();
audio.src = '2.mp3';
audio.controls = true;
audio.autoplay = true;
audio.loop=true;
var context = new webkitAudioContext();
var analyser = context.createAnalyser();
var source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
var freqData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(freqData);
//visualization using freqData
when i change the source to :
source = context.createBufferSource();
it does not show anything.
So is there way to visualize it and yet without error and enable it to resume again and again?
Actually, I believe the problem is that you're trying to create a SECOND web audio node for the same media element. (Your code, when clicked, re-sets the SRC, controls, etc., but it's not creating a new Audio().) You should either hang on to the MediaElementAudioSourceNode you created, or create new Audio elements.
E.g.:
var context = new webkitAudioContext();
var analyser = context.createAnalyser();
var source = null;
var audio0 = new Audio();
$("#0").click(function(){
audio0.src = 'http://www.bornemark.se/bb/mp3_demos/PoA_Sorlin_-_Stay_Up.mp3';
audio0.controls = true;
audio0.autoplay = true;
audio0.loop = true;
if (source==null) {
source = context.createMediaElementSource(audio0);
source.connect(analyser);
analyser.connect(context.destination);
}
});​
Hope that helps!
-Chris Wilson
From what I can tell, this is likely because the MediaElementSourceNode may only be able to take in an Audio that isn't already playing. The Audio object is declared outside of the click handler, so you're trying to analyze audio that's in the middle of playing the second time you click.
Note that the API doesn't seem to specify this, so I'm not 100% sure, but this makes intuitive sense.

How to use navigateToUrl to access html files relative to the site root?

I try to make an intro animation inside a website, and when the animation is done or when you push the Skip button, it navigates to the index.html file from the site root.
So I have in my site root the folder Flash, where the intro.swf is, and within the intro.swf I called the navigateToURL(new URLRequest("..\index.html"), "_self"); method. Now it's not working. Can you tell how to define the URL request please?
Thanks.
Have you tried this:
navigateToURL(new URLRequest("../index.html"), "_self");
Is using a backslash just a typo?
You know, I once had a weird scoping issue in Flex. The solution was to force an absolute URL by parsing the loaderInfo.loaderURL manually. A simple version might be:
function getAbsoluteURL( pathFromSwf:String, swfURL:String ):String
{
// if pathFromSwf is already a URL, then just return that.
if( pathFromSwf.match( /^(http.{3}[^\/]{5,})\/(.*)$/ ) ) return pathFromSwf;
// this may need to be customized based on your extension/server settings.
var basePath:Array = swfURL.substr( 0, swfURL.indexOf( ".swf" ) ).split( "/" );
basePath.pop(); // clear out the swf's name.
var altPath:Array = pathFromSwf.split( "/" );
for( var i:int = 0; i < altPath.length; i++ )
{
// ".." subtracts from the path/
if( altPath[ i ] == ".." ) basePath.pop();
// otherwise append
else basePath.push( altPath[ i ] );
}
return basePath.join( "/" );
}
location of your swf file:
loaderInfo.loaderURL