I need to determine which connection type a device is using.
Distinguishing between WIFI and 3G doesn't seem to be a problem on iOS (using the NetworkInfo ANE) and Android (using the native NetworkInfo class) but I've got no clue how to further distinguish between a fast (3G, 4G) and slow (EDGE) connection.
Is there a way to do this with Adobe Air?
Try this for detecting Mobile vs. Wifi on iOS. This requires the Adobe native extension "NetworkInfo"
import com.adobe.nativeExtensions.Networkinfo.InterfaceAddress;
import com.adobe.nativeExtensions.Networkinfo.NetworkInfo;
import com.adobe.nativeExtensions.Networkinfo.NetworkInterface;
var vNetworkInterfaces:Object;
if (flash.net.NetworkInfo.isSupported)
{
vNetworkInterfaces = getDefinitionByName('flash.net.NetworkInfo')['networkInfo']['findInterfaces']();
mytrace("fall 1" );
}
else
{
vNetworkInterfaces = getDefinitionByName('com.adobe.nativeExtensions.Networkinfo.NetworkInfo')['networkInfo']['findInterfaces']();
mytrace("fall 2" );
}
var hasWifi: Boolean = false;
var hasMobile: Boolean = false;
for each (var networkInterface:Object in vNetworkInterfaces)
{
if ( networkInterface.active && (networkInterface.name == "en0" || networkInterface.name == "en1") ) hasWifi = true;
if ( networkInterface.active && (networkInterface.name == "pdp_ip0" || networkInterface.name == "pdp_ip1" || networkInterface.name == "pdp_ip2") ) hasMobile = true;
mytrace( "active: " + networkInterface.active );
mytrace( "displayName: " + networkInterface.displayName );
mytrace( "name: " + networkInterface.name );
mytrace( "hwAddress: " + networkInterface.hardwareAddress );
mytrace( "--------------------" );
}
mytrace( "has Mobile Internet: " + hasMobile );
mytrace( "has Wifi Internet: " + hasWifi );
I dunno if there's a solution a direct solution but when you're downloading a file you could check the speed at which file is downloaded, by using getTimer function in conjunction with loaded bytes and a ratio of total bytes.
Example
function init()
{
startTime = getTimer();
loader = new Loader();
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoaderInit);
loader.load("some-site.com/myasset.png");
}
function onLoaderInit(e:ProgressEvent)
{
$timePassed = (getTimer() - startTime) * 0.001; //it's in millisecounds convert to secounds
$newBytes = loader.contentLoaderInfo.bytesLoaded - oldBytes;
var $rate:Number = $newBytes * $timePassed; //returns a value of bytes per sec.
startTime = getTimer();
oldBytes = loader.contentLoaderInfo.bytesLoaded;
}
Nice... if it works... dunno if there's a solution a direct solution but when you're downloading a file you could check the speed at which file is downloaded, by using getTimer function in conjunction with loaded bytes and a ratio of total bytes
Related
I'm wondering how website like this one : https://ping.eu/ping/ manage to make our ip ping an other ip and get the result.
Someone have an idea ?
Thanks
It Doesn't. A PHP script(on the server) will most likely do it with "PHP Sockets". Have a look at
this: https://www.php.net/manual/en/sockets.examples.php
Else it could use exec() function, but that would be a security flaw.
So to answer your question: The website will ping the IP address not the 'client'
If you want to ping a server, i.e. an actual web address/URL like www.google.com, you can look at this JSFiddle http://jsfiddle.net/GSSCD/203/ or GitHub repository https://github.com/jdfreder/pingjs.
Here's some code from the JSFiddle:
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
Another way to ping a server/web address is to use JavaScript and the XMLHttpRequest() function it supports:
HTML:
<div id="result"></div>
JavaScript:
function http_ping(fqdn) {
var NB_ITERATIONS = 4; // number of loop iterations
var MAX_ITERATIONS = 5; // beware: the number of simultaneous XMLHttpRequest is limited by the browser!
var TIME_PERIOD = 1000; // 1000 ms between each ping
var i = 0;
var over_flag = 0;
var time_cumul = 0;
var REQUEST_TIMEOUT = 9000;
var TIMEOUT_ERROR = 0;
document.getElementById('result').innerHTML = "HTTP ping for " + fqdn + "</br>";
var ping_loop = setInterval(function() {
// let's change non-existent URL each time to avoid possible side effect with web proxy-cache software on the line
url = "http://" + fqdn + "/a30Fkezt_77" + Math.random().toString(36).substring(7);
if (i < MAX_ITERATIONS) {
var ping = new XMLHttpRequest();
i++;
ping.seq = i;
over_flag++;
ping.date1 = Date.now();
ping.timeout = REQUEST_TIMEOUT; // it could happen that the request takes a very long time
ping.onreadystatechange = function() { // the request has returned something, let's log it (starting after the first one)
if (ping.readyState == 4 && TIMEOUT_ERROR == 0) {
over_flag--;
if (ping.seq > 1) {
delta_time = Date.now() - ping.date1;
time_cumul += delta_time;
document.getElementById('result').innerHTML += "</br>http_seq=" + (ping.seq-1) + " time=" + delta_time + " ms</br>";
}
}
}
ping.ontimeout = function() {
TIMEOUT_ERROR = 1;
}
ping.open("GET", url, true);
ping.send();
}
if ((i > NB_ITERATIONS) && (over_flag < 1)) { // all requests are passed and have returned
clearInterval(ping_loop);
var avg_time = Math.round(time_cumul / (i - 1));
document.getElementById('result').innerHTML += "</br> Average ping latency on " + (i-1) + " iterations: " + avg_time + "ms </br>";
}
if (TIMEOUT_ERROR == 1) { // timeout: data cannot be accurate
clearInterval(ping_loop);
document.getElementById('result').innerHTML += "<br/> THERE WAS A TIMEOUT ERROR <br/>";
return;
}
}, TIME_PERIOD);
}
But, of course, these are web addresses, not IP addresses, so I'm not sure if that's what you're aiming for. I'm also not sure if you're looking for the amount of time spent to get the connection and the number of packets and bytes sent and received, or if you just want to validate the connection. The above code does all of those things. For IP addresses, you can try an AJAX request to ping a server, which only sees if there is a connection using YOUR SERVER'S IP address, NOT THE USER'S CLIENT, like this:
client --AJAX-- yourserver --ICMP ping-- targetservers
You could also try:
Using a Java applet with isReachable
Writing a server-side script which pings, and using AJAX to communicate to your server-side script
You might also be able to ping in Flash (using ActionScript)
One last hypothetical and unorthodox way to get an IP address is to inspect and view the source of the website you mentioned and copy some code, mostly JavaScript, and test it on your end and try to implement it.
I am facing a problem with FLVPlayback complete event with AS3 publishing for FlashPlayer 11.1
The trouble is that after a few seconds of the video starts the complete event is triggered and the problem always occurs only after a few hours of playing a playlist of videos.
Some code here:
var my_player:FLVPlayback = new FLVPlayback();
function makePlayer():void{
my_player.scaleMode = "exactFit";
my_player.x = video_x;
my_player.y = video_y;
my_player.width = video_width;
my_player.height = video_height;
if(bBordi)
my_player.mask = mask_mc;
video.addChild(my_player);
my_player.source = my_path + my_videos[nVideo].#URL;
my_player.addEventListener(fl.video.VideoEvent.COMPLETE, completePlay);
my_player.volume=video_volume;
}
function completePlay(e:fl.video.VideoEvent):void
{
if(!my_player.stopped)
return;
trace("VIDEO ENDED: " + my_path + my_videos[nVideo].#URL)
nVideo++;
if(nVideo >= my_total)
nVideo = 0;
playPlayer();
}
function playPlayer():void{
my_player.source=(my_path + my_videos[nVideo].#URL);
my_player.play();
}
Publishing for FlashPlayer 11.8 resolve the problem.
I am using Recorder.js to record audio but there is terrible feedback if I don't use a headset. There is even a little feedback if I use my apple earphones where the mic is a bit closer to the ear piece. Is there a way to lower the mic/recording volume and prevent the feedback?
If you have access to the gain_node - you can control the output speaker volume
put this into your html (optional)
<p>Volume</p>
<input id="volume" type="range" min="0" max="1" step="0.1" value="0.5"/>
then do similar to following where U have access to the gain_node
document.getElementById('volume').addEventListener('change', function() {
var curr_volume = this.value;
gain_node.gain.value = curr_volume;
console.log("curr_volume ", curr_volume);
});
below I bundle above into a set of calls to Web Audio API where I have a UI widget to change the volume while it listens to your microphone ... turn DOWN your volume before running this !
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>capture microphone then show time & frequency domain output</title>
<script type="text/javascript">
var webaudio_tooling_obj = function () {
var audioContext = new AudioContext();
console.log("audio is starting up ...");
var BUFF_SIZE_RENDERER = 16384;
var SIZE_SHOW = 3; // number of array elements to show in console output
var audioInput = null,
microphone_stream = null,
gain_node = null,
script_processor_node = null,
script_processor_analysis_node = null,
analyser_node = null;
if (!navigator.getUserMedia)
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia){
navigator.getUserMedia({audio:true},
function(stream) {
start_microphone(stream);
},
function(e) {
alert('Error capturing audio.');
}
);
} else { alert('getUserMedia not supported in this browser.'); }
// ---
function show_some_data(given_typed_array, num_row_to_display, label) {
var size_buffer = given_typed_array.length;
var index = 0;
console.log("__________ " + label);
if (label === "time") {
for (; index < num_row_to_display && index < size_buffer; index += 1) {
var curr_value_time = (given_typed_array[index] / 128) - 1.0;
console.log(curr_value_time);
}
} else if (label === "frequency") {
for (; index < num_row_to_display && index < size_buffer; index += 1) {
console.log(given_typed_array[index]);
}
} else {
throw new Error("ERROR - must pass time or frequency");
}
}
function process_microphone_buffer(event) {
var i, N, inp, microphone_output_buffer;
// not needed for basic feature set
// microphone_output_buffer = event.inputBuffer.getChannelData(0); // just mono - 1 channel for now
}
function start_microphone(stream){
gain_node = audioContext.createGain();
gain_node.connect( audioContext.destination );
microphone_stream = audioContext.createMediaStreamSource(stream);
microphone_stream.connect(gain_node);
script_processor_node = audioContext.createScriptProcessor(BUFF_SIZE_RENDERER, 1, 1);
script_processor_node.onaudioprocess = process_microphone_buffer;
microphone_stream.connect(script_processor_node);
// --- enable volume control for output speakers
document.getElementById('volume').addEventListener('change', function() {
var curr_volume = this.value;
gain_node.gain.value = curr_volume;
console.log("curr_volume ", curr_volume);
});
// --- setup FFT
script_processor_analysis_node = audioContext.createScriptProcessor(2048, 1, 1);
script_processor_analysis_node.connect(gain_node);
analyser_node = audioContext.createAnalyser();
analyser_node.smoothingTimeConstant = 0;
analyser_node.fftSize = 2048;
microphone_stream.connect(analyser_node);
analyser_node.connect(script_processor_analysis_node);
var buffer_length = analyser_node.frequencyBinCount;
var array_freq_domain = new Uint8Array(buffer_length);
var array_time_domain = new Uint8Array(buffer_length);
console.log("buffer_length " + buffer_length);
script_processor_analysis_node.onaudioprocess = function() {
// get the average for the first channel
analyser_node.getByteFrequencyData(array_freq_domain);
analyser_node.getByteTimeDomainData(array_time_domain);
// draw the spectrogram
if (microphone_stream.playbackState == microphone_stream.PLAYING_STATE) {
show_some_data(array_freq_domain, SIZE_SHOW, "frequency");
show_some_data(array_time_domain, SIZE_SHOW, "time"); // store this to record to aggregate buffer/file
}
};
}
}(); // webaudio_tooling_obj = function()
</script>
</head>
<body>
<p>Volume</p>
<input id="volume" type="range" min="0" max="1" step="0.1" value="0.0"/>
</body>
</html>
Of course no UI widget is necessary as you have programmatic control over the output volume and so to go silent you can either disconnect the gain node or just set it low
Their example page (example_simple_exportwav.html) states that you should wear headphones or turn down the volume.
Also before you enable microphone input either plug in headphones or
turn the volume down if you want to avoid ear splitting feedback!
You could mute or decrease the volume of the speakers during recording:
Muting a HTML5 audio element using a custom button
How to mute all sound in a page with JS?
How to set the loudness of HTML5 audio?
I also tested a few examples and never experienced feedback with my laptop speakers. Could you post your code so we could test it live?
Record and Export Audio, Video files in browser using Web Audio API with Recorder.js - demo at the bottom
http://webaudiodemos.appspot.com/AudioRecorder/index.html via Web Audio Demos
localStorageTest stores an incrementally increasing value in localStorage until it hits the localStorage size limits of the browser.
function localStorageTest(key, len) {
var value = window.localStorage.getItem(key);
value = (value == null)?"":value;
var numIters = len - value.length;
while(numIters--) {
value += "1";
window.localStorage.setItem(key, value);
if (window.localStorage.getItem(key) != value) {
console.log("limit reached at " + (value.length-1).toString() + " bytes");
break;
}
}
console.log("stored " + value.length + " bytes");
}
Chrome:
localStorageTest("1", 80000);
<browser crashed>
Firefox:
localStorageTest("1", 50000);
<browser crashed>
Suspecting an increased usage of browser memory, I wrote localStorageIncrementalTest which does the same thing as localStorageTest, but puts idle periods of 5 seconds in between its operations, using a setTimeOut call.
var increment = 5000;
function localStorageIncrementalTest(key, len) {
var value = window.localStorage.getItem(key);
value = (value == null)?"":value;
var numIters = len - value.length;
var limitReached = false;
while(numIters--) {
value += "1";
window.localStorage.setItem(key, value);
if (window.localStorage.getItem(key) != value) {
console.log("limit reached at " + (value.length-1).toString() + " bytes");
limitReached = true;
break;
}
}
console.log("stored " + value.length + " bytes");
if (!limitReached) {
setTimeout(function() {
localStorageIncrementalTest(key, len+increment);
}, 5000);
}
}
Chrome :
localStorageIncrementalTest("1", 30000);
stored 30000 bytes
stored 35000 bytes
...
stored 1800000 bytes
<browser crashed>
Firefox :
localStorageIncrementalTest("1", 30000);
stored 30000 bytes
stored 35000 bytes
...
stored 60000 bytes
<browser crashed>
So localStorageIncrementalTest allows us to store more in localStorage than localStorageTest before crashing the browser.
Can anyone explain the reasons behind the browser crash, and a possible solution to avoid the same ?
I'm using Chrome 28.0.1500.71, and Firefox 26.0
Update :
function getRandomValue(size) {
var value = "";
for (var i = 0; i < size; i++) {
value += Math.ceil(Math.random()*5);
}
return value;
}
function localStorageTest2() {
for (var i = 0; i < 70000; i++) {
window.localStorage.setItem("1", getRandomValue(20000));
}
}
Chrome :
localStorageTest2();
<browser crashed>
Firefox :
localStorageTest2();
<browser crashed>
Testing localStorage2 too caused the browser to crash.
I am not sure why the browsers crash, but it is worth reporting it at crbug.com and bugzilla.mozilla.com.
However, localStorage is not meant for this kind of usage. It is a synchronous API which puts a lot of strain on the browser when it is used, especially when it is used so frequently and will cause the page to perform badly in general.
Also, your test would not yield the right results - setItem(x, y) would throw an exception when you exceed the limit. localStorage.setItem(x, y); if (y == localStorage.getItem(x)) { ... } will never reach the if part, because it will throw an exception beforehand when the limit is reached.
The alternatives are simple variables, server storage or IndexedDB.
Chrome also has the FileSystem API and the Web SQL Databases API, but it is best not to rely on those, because they are not supported in other browsers.
Im trying too load new messages every second, but new messages are doubled everytime they are loaded, I suppose because the timer is completed before the php is executed?
so I tried to add
if (checker != "" + idstored + "done") {
checker = "" + idstored + "done";
so that once the timer completes, it changes the checker so that when the timer restarts and finishes again it would not execute again... but it stopped checking for all new messages... any tips??
var count:Timer = new Timer(1000, 1);
count.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
count.start();
var checker;
function onTimerComplete(event:TimerEvent):void{
if (checker != "" + idstored + "done") {
checker = "" + idstored + "done";
var variables_cc:URLVariables = new URLVariables();
var varSend_cc:URLRequest = new URLRequest("chat.php");
varSend_cc.method = URLRequestMethod.POST;
varSend_cc.data = variables_cc;
var varLoader_cc:URLLoader = new URLLoader;
varLoader_cc.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader_cc.addEventListener(Event.COMPLETE, completeHandler_cc);
function completeHandler_cc(event:Event):void{
if (event.target.data.statusline == "is_new") {
stored_id_txt.text = "" + event.target.data.stored_id;
status_txt.text = "" + event.target.data.statusline;
returnline.text = "" + event.target.data.returnBody;
checker.text = checker;
splitByDelimiter(event.target.data.returnBody);
idstored = event.target.data.stored_id;
checker = "refresh";
}
}}
// ready the last_refresh_time variable for sending to PHP
variables_cc.requester = "chat_check";
variables_cc.stored_id = idstored;
varLoader_cc.load(varSend_cc);
count.reset();
count.start();
}
You get errors becouse you sometimes try to start new download when the previous is not finished. It's not wise to do something latency dependent every 1 second real time. You need to start something, wait for it to finish, and then start it again.
removeEventListener of the timer after it launches (inside onTimerComplete function) and stop the timer and reset it. qddEventListener to the timer and start it after the data is downloaded (inside completeHangler_cc function).