trigger is called in beginning - audio

I have a sound that gets triggered with OnTriggerEnter, and picking up whether sound is playing to turn sprite renderer on/off.
For some reason, when I start the game, the sound starts playing (which should only be getting called by the trigger).
I checked the trigger with the players tag and debug.log to console, and found that the trigger method isn't being called at the start. But, for some reason, the sound is getting played at the start and when I hit the trigger(but not turning the sprite renderer back on).
FlagScript
#pragma strict
var Sprite2 : Sprite; //second sprite to renderer
var sr : SpriteRenderer;
var hasBeenHit : boolean = false;
var flagCollisionSounderies: AudioSource;
var flagCollisionSound : AudioClip = null;
private var applauseRef: ApplauseScript;
private var go: GameObject;
var count : int = 0;
function Start () {
//access the spriteRenderer
flagCollisionSound = flagCollisionSounderies.clip;
sr = GetComponent(SpriteRenderer);
go = GameObject.Find("ClapMaster");
applauseRef = go.GetComponent(typeof(ApplauseScript));
//Debug.Log("bool: "+flagCollisionSounderies.isPlaying); //true already
}
function OnTriggerEnter2D(coll: Collider2D){
//Debug.Log("flagtriggered");
//change the flag to other flag
sr.sprite = Sprite2;
if (coll.gameObject.tag == "Player"){
Debug.Log("poos");
if (hasBeenHit == false){
GameMaster.setFlags(GameMaster.getFlags()-1);
GameMaster.addPointsToScore(100);
if (flagCollisionSound != null){
flagCollisionSounderies.PlayClipAtPoint(flagCollisionSound, transform.position);
//Debug.Log("bool:" + flagCollisionSounderies.isPlaying);
applauseRef.animRenderer.enabled = true;
}
}
}
hasBeenHit = true;
}
function Update(){
if(!flagCollisionSounderies.isPlaying){
applauseRef.animRenderer.enabled = false;
//applauseRef.playApplauseAnim = false;
}else{
//Debug.Log("sounderies detecteddFsdlfkjsdlfksjdflksdjflkj1123123");
applauseRef.animRenderer.enabled = true;
//applauseRef.playApplauseAnim = true;
}
}
Applause Script
#pragma strict
var SpriteLoad: Sprite[];
static var animSprites : Sprite[];
static var playerScriptRef: newplayer;
static var animRenderer: SpriteRenderer;
//private static var i : int = 7;
private static var frame : int = 3;
private static var Ymove: float = 0f;
private static var goingUp: boolean = false;
static var playApplauseAnim: boolean;
function Start(){
animRenderer = GetComponent(SpriteRenderer);
animSprites = SpriteLoad;
playerScriptRef = GameObject.Find("Player 1").GetComponent(newplayer);
//animRenderer.enabled = false;
//playApplauseAnim = false;
}
function Update(){
PicMover();
frame = (frame +1 ) % 4;
animRenderer.sprite = animSprites[frame];
}
static function PicMover(){
if(Ymove < 20 && goingUp){
Ymove++;
}else if(Ymove > -20 && !goingUp){
Ymove--;
}else if(Ymove == 20){
goingUp = false;
}else if(Ymove == -20){
goingUp = true;
}
animRenderer.transform.position = new Vector2(10,10);
}

Related

How I can Add Text inside Frame TabbedRenderer in Xamarin iOS

I am customizing Badge in TabbedPage. I have now added the red dot from inheriting UIView. However how can I Add Text inside that Frame. Xamarin iOS
MyTabbedPageRenderer.cs
public static class TabbarExtensions
{
readonly static int tabBarItemTag = 9999;
public static void addItemBadge(this UITabBar tabbar, int index)
{
if (tabbar.Items != null && tabbar.Items.Length == 0) return;
if (index >= tabbar.Items.Length) return;
removeItemBadge(tabbar, index);
var badgeView = new UIView();
badgeView.Tag = tabBarItemTag + index;
badgeView.Layer.CornerRadius = 7;
badgeView.BackgroundColor = UIColor.Red;
var tabFrame = tabbar.Frame;
var percentX = (index + 0.56) / tabbar.Items.Length;
var x = percentX * tabFrame.Width;
var y = tabFrame.Height * 0.05;
badgeView.Frame = new CoreGraphics.CGRect(x, y, 13, 13);
tabbar.AddSubview(badgeView);
//var badgeView = new UILabel();
//badgeView.Tag = tabBarItemTag + index;
//badgeView.BackgroundColor = UIColor.Red;
//var tabFrame = tabbar.Frame;
//var percentX = (index + 0.56) / tabbar.Items.Length;
//var x = percentX * tabFrame.Width;
//var y = tabFrame.Height * 0.05;
//badgeView.Text = "1";
//badgeView.TextAlignment = UITextAlignment.Center;
//badgeView.TextColor = UIColor.White;
//badgeView.Font = UIFont.SystemFontOfSize(10);
//tabbar.AddSubview(badgeView);
}
public static bool removeItemBadge(this UITabBar tabbar, int index)
{
foreach (var subView in tabbar.Subviews)
{
if (subView.Tag == tabBarItemTag + index)
{
subView.RemoveFromSuperview();
return true;
}
}
return false;
}
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
MessagingCenter.Subscribe<object, int>(this, "Add", (obj, index) => {
TabBar.addItemBadge(index);
});
MessagingCenter.Subscribe<object, int>(this, "Remove", (obj, index) => {
TabBar.removeItemBadge(index);
});
}
MainView.xaml.cs
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<object, int>(this, "Add", 2);
}
As in my code above I tried with UILabel. However I cannot set CornerRadius for Label
Summarize how I can Add Text inside Frame. Or how can I set CornerRadius for Lable in Xamarin iOS.
Thank you!
Description picture:
If I use UILabel, I cannot set CornerRadius
If I use UIView
For UILabel, you could set the CornerRadius using the following:
badgeView.Layer.CornerRadius = 7;
badgeView.Layer.MasksToBounds = true;//add this line
For more info, you could refer to masksToBounds.
Hope it works for you.

NAudio Mp3 decoding click and pops

I followed this NAudio Demo modified to play ShoutCast.
In my full code I have to resample the incoming audio and stream it again over the network to a network player. Since I get many "clicks and pops", I came back to the demo code and I found that these artifacts are originated after the decoding block.
If I save the incoming stream in mp3 format, it is pretty clear.
When I save the raw decoded data (without other processing than the decoder) I get many audio artifacts.
I wonder whether I am doing some error, even if my code is almost equal to the NAudio demo.
Here the function from the example as modified by me to save the raw data. It is called as a new Thread.
private void StreamMP3(object state)
{
//Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//SettingsSection section = (SettingsSection)config.GetSection("system.net/settings");
this.fullyDownloaded = false;
string url = "http://icestreaming.rai.it/5.mp3";//(string)state;
webRequest = (HttpWebRequest)WebRequest.Create(url);
int metaInt = 0; // blocksize of mp3 data
int framesize = 0;
webRequest.Headers.Clear();
webRequest.Headers.Add("GET", "/ HTTP/1.0");
// needed to receive metadata informations
webRequest.Headers.Add("Icy-MetaData", "1");
webRequest.UserAgent = "WinampMPEG/5.09";
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.RequestCanceled)
{
ShowError(e.Message);
}
return;
}
byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
try
{
// read blocksize to find metadata block
metaInt = Convert.ToInt32(resp.GetResponseHeader("icy-metaint"));
}
catch
{
}
IMp3FrameDecompressor decompressor = null;
byteOut = createNewFile(destPath, "salva", "raw");
try
{
using (var responseStream = resp.GetResponseStream())
{
var readFullyStream = new ReadFullyStream(responseStream);
readFullyStream.metaInt = metaInt;
do
{
if (mybufferedWaveProvider != null && mybufferedWaveProvider.BufferLength - mybufferedWaveProvider.BufferedBytes < mybufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
{
Debug.WriteLine("Buffer getting full, taking a break");
Thread.Sleep(500);
}
else
{
Mp3Frame frame = null;
try
{
frame = Mp3Frame.LoadFromStream(readFullyStream, true);
if (metaInt > 0)
UpdateSongName(readFullyStream.SongName);
else
UpdateSongName("No Song Info in Stream...");
}
catch (EndOfStreamException)
{
this.fullyDownloaded = true;
// reached the end of the MP3 file / stream
break;
}
catch (WebException)
{
// probably we have aborted download from the GUI thread
break;
}
if (decompressor == null)
{
// don't think these details matter too much - just help ACM select the right codec
// however, the buffered provider doesn't know what sample rate it is working at
// until we have a frame
WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
decompressor = new AcmMp3FrameDecompressor(waveFormat);
this.mybufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
this.mybufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(200); // allow us to get well ahead of ourselves
framesize = (decompressor.OutputFormat.Channels * decompressor.OutputFormat.SampleRate * (decompressor.OutputFormat.BitsPerSample / 8) * 20) / 1000;
//this.bufferedWaveProvider.BufferedDuration = 250;
}
int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
//Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
mybufferedWaveProvider.AddSamples(buffer, 0, decompressed);
while (mybufferedWaveProvider.BufferedDuration.Milliseconds >= 20)
{
byte[] read = new byte[framesize];
mybufferedWaveProvider.Read(read, 0, framesize);
byteOut.Write(read, 0, framesize);
}
}
} while (playbackState != StreamingPlaybackState.Stopped);
Debug.WriteLine("Exiting");
// was doing this in a finally block, but for some reason
// we are hanging on response stream .Dispose so never get there
decompressor.Dispose();
}
}
finally
{
if (decompressor != null)
{
decompressor.Dispose();
}
}
}
OK i found the problem. I included the shoutcast metadata to the MP3Frame.
See the comment "HERE I COLLECT THE BYTES OF THE MP3 FRAME" to locate the correct point to get the MP3 frame with no streaming metadata.
The following code runs without audio artifacts:
private void SHOUTcastReceiverThread()
{
//-*- String server = "http://216.235.80.18:8285/stream";
//String serverPath = "/";
//String destPath = "C:\\temp\\"; // destination path for saved songs
HttpWebRequest request = null; // web request
HttpWebResponse response = null; // web response
int metaInt = 0; // blocksize of mp3 data
int count = 0; // byte counter
int metadataLength = 0; // length of metadata header
string metadataHeader = ""; // metadata header that contains the actual songtitle
string oldMetadataHeader = null; // previous metadata header, to compare with new header and find next song
//CircularQueueStream framestream = new CircularQueueStream(2048);
QueueStream framestream = new QueueStream();
framestream.Position = 0;
bool bNewSong = false;
byte[] buffer = new byte[512]; // receive buffer
byte[] dec_buffer = new byte[decSIZE];
Mp3Frame frame;
IMp3FrameDecompressor decompressor = null;
Stream socketStream = null; // input stream on the web request
// create web request
request = (HttpWebRequest)WebRequest.Create(server);
// clear old request header and build own header to receive ICY-metadata
request.Headers.Clear();
request.Headers.Add("GET", serverPath + " HTTP/1.0");
request.Headers.Add("Icy-MetaData", "1"); // needed to receive metadata informations
request.UserAgent = "WinampMPEG/5.09";
// execute request
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
// read blocksize to find metadata header
metaInt = Convert.ToInt32(response.GetResponseHeader("icy-metaint"));
try
{
// open stream on response
socketStream = response.GetResponseStream();
var readFullyStream = new ReadFullyStream(socketStream);
frame = null;
// rip stream in an endless loop
do
{
if (IsBufferNearlyFull)
{
Debug.WriteLine("Buffer getting full, taking a break");
Thread.Sleep(500);
frame = null;
}
else
{
int bufLen = readFullyStream.Read(buffer, 0, buffer.Length);
try
{
if (framestream.CanRead && framestream.Length > 512)
frame = Mp3Frame.LoadFromStream(framestream);
else
frame = null;
}
catch (Exception ex)
{
frame = null;
}
if (bufLen < 0)
{
Debug.WriteLine("Buffer error 1: exit.");
return;
}
// processing RAW data
for (int i = 0; i < bufLen; i++)
{
// if there is a header, the 'headerLength' would be set to a value != 0. Then we save the header to a string
if (metadataLength != 0)
{
metadataHeader += Convert.ToChar(buffer[i]);
metadataLength--;
if (metadataLength == 0) // all metadata informations were written to the 'metadataHeader' string
{
string fileName = "";
string fileNameRaw = "";
// if songtitle changes, create a new file
if (!metadataHeader.Equals(oldMetadataHeader))
{
// flush and close old byteOut stream
if (byteOut != null)
{
byteOut.Flush();
byteOut.Close();
byteOut = null;
}
if (byteOutRaw != null)
{
byteOutRaw.Flush();
byteOutRaw.Close();
byteOutRaw = null;
}
timeStart = timeEnd;
// extract songtitle from metadata header. Trim was needed, because some stations don't trim the songtitle
//fileName = Regex.Match(metadataHeader, "(StreamTitle=')(.*)(';StreamUrl)").Groups[2].Value.Trim();
fileName = Regex.Match(metadataHeader, "(StreamTitle=')(.*)(';)").Groups[2].Value.Trim();
// write new songtitle to console for information
if (fileName.Length == 0)
fileName = "shoutcast_test";
fileNameRaw = fileName + "_raw";
framestream.reSetPosition();
SongChanged(this, metadataHeader);
bNewSong = true;
// create new file with the songtitle from header and set a stream on this file
timeEnd = DateTime.Now;
if (bWrite_to_file)
{
byteOut = createNewFile(destPath, fileName, "mp3");
byteOutRaw = createNewFile(destPath, fileNameRaw, "raw");
}
timediff = timeEnd - timeStart;
// save new header to 'oldMetadataHeader' string, to compare if there's a new song starting
oldMetadataHeader = metadataHeader;
}
metadataHeader = "";
}
}
else // write mp3 data to file or extract metadata headerlength
{
if (count++ < metaInt) // write bytes to filestream
{
//HERE I COLLECT THE BYTES OF THE MP3 FRAME
framestream.Write(buffer, i, 1);
}
else // get headerlength from lengthbyte and multiply by 16 to get correct headerlength
{
metadataLength = Convert.ToInt32(buffer[i]) * 16;
count = 0;
}
}
}//for
if (bNewSong)
{
decompressor = createDecompressor(frame);
bNewSong = false;
}
if (frame != null && decompressor != null)
{
framedec(decompressor, frame);
}
// fine Processing dati RAW
}//Buffer is not full
SHOUTcastStatusProcess();
} while (playbackState != StreamingPlaybackState.Stopped);
} //try
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (byteOut != null)
byteOut.Close();
if (socketStream != null)
socketStream.Close();
if (decompressor != null)
{
decompressor.Dispose();
decompressor = null;
}
if (null != request)
request.Abort();
if (null != framestream)
framestream.Dispose();
if (null != bufferedWaveProvider)
bufferedWaveProvider.ClearBuffer();
//if (null != bufferedWaveProviderOut)
// bufferedWaveProviderOut.ClearBuffer();
if (null != mono16bitFsinStream)
{
mono16bitFsinStream.Close();
mono16bitFsinStream.Dispose();
}
if (null != middleStream2)
{
middleStream2.Close();
middleStream2.Dispose();
}
if (null != resampler)
resampler.Dispose();
}
}
public class QueueStream : MemoryStream
{
long ReadPosition = 0;
long WritePosition = 0;
public QueueStream() : base() { }
public override int Read(byte[] buffer, int offset, int count)
{
Position = ReadPosition;
var temp = base.Read(buffer, offset, count);
ReadPosition = Position;
return temp;
}
public override void Write(byte[] buffer, int offset, int count)
{
Position = WritePosition;
base.Write(buffer, offset, count);
WritePosition = Position;
}
public void reSetPosition()
{
WritePosition = 0;
ReadPosition = 0;
Position = 0;
}
}
private void framedec(IMp3FrameDecompressor decompressor, Mp3Frame frame)
{
int Ndecoded_samples = 0;
byte[] dec_buffer = new byte[decSIZE];
Ndecoded_samples = decompressor.DecompressFrame(frame, dec_buffer, 0);
bufferedWaveProvider.AddSamples(dec_buffer, 0, Ndecoded_samples);
NBufferedSamples += Ndecoded_samples;
brcnt_in.incSamples(Ndecoded_samples);
if (Ndecoded_samples > decSIZE)
{
Debug.WriteLine(String.Format("Too many samples {0}", Ndecoded_samples));
}
if (byteOut != null)
byteOut.Write(frame.RawData, 0, frame.RawData.Length);
if (byteOutRaw != null) // as long as we don't have a songtitle, we don't open a new file and don't write any bytes
byteOutRaw.Write(dec_buffer, 0, Ndecoded_samples);
frame = null;
}
private IMp3FrameDecompressor createDecompressor(Mp3Frame frame)
{
IMp3FrameDecompressor dec = null;
if (frame != null)
{
// don't think these details matter too much - just help ACM select the right codec
// however, the buffered provider doesn't know what sample rate it is working at
// until we have a frame
WaveFormat srcwaveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
dec = new AcmMp3FrameDecompressor(srcwaveFormat);
bufferedWaveProvider = new BufferedWaveProvider(dec.OutputFormat);// decompressor.OutputFormat
bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(400); // allow us to get well ahead of ourselves
// ------------------------------------------------
//Create an intermediate format with same sampling rate, 16 bit, mono
middlewavformat = new WaveFormat(dec.OutputFormat.SampleRate, 16, 1);
outwavFormat = new WaveFormat(Fs_out, 16, 1);
// wave16ToFloat = new Wave16ToFloatProvider(provider); // I have tried with and without this converter.
wpws = new WaveProviderToWaveStream(bufferedWaveProvider);
//Check middlewavformat.Encoding == WaveFormatEncoding.Pcm;
mono16bitFsinStream = new WaveFormatConversionStream(middlewavformat, wpws);
middleStream2 = new BlockAlignReductionStream(mono16bitFsinStream);
resampler = new MediaFoundationResampler(middleStream2, outwavFormat);
}
return dec;
}

Error #1069: Property Pertanyaan0 not found on String and there is no default value

I stuck here please help, i'm new in flash, using adobe flash cs5.5
Here's the code :
import flash.net.URLLoaderDataFormat;
import flash.events.DataEvent;
stop();
alert_mc.visible = false;
alert_mc.ok_btn.visible = false;
var score:Number = 0;
var jawaban;
var nextQst:Number = 0;
var i:Number = 0;
a_btn.addEventListener(MouseEvent.CLICK,btna);
function btna(ev:MouseEvent):void
{
cekJawaban("a");
}
b_btn.addEventListener(MouseEvent.CLICK,btnb);
function btnb(ev:MouseEvent):void
{
cekJawaban("b");
}
c_btn.addEventListener(MouseEvent.CLICK,btnc);
function btnc(ev:MouseEvent):void
{
cekJawaban("c");
}
d_btn.addEventListener(MouseEvent.CLICK,btnd);
function btnd(ev:MouseEvent):void
{
cekJawaban("d");
}
var qvar_lv:URLLoader = new URLLoader();
qvar_lv.dataFormat = URLLoaderDataFormat.TEXT;// Step 1
qvar_lv.load(new URLRequest("DaftarSoal.txt")); // Step 2
qvar_lv.addEventListener(Event.COMPLETE, onComplete); // Step 3
function onComplete (event:Event):void // Step 4
{
var faq:String = event.target.data; // Step 5
trace("Success"+faq);
if (faq["Pertanyaan"+i] != undefined) {
no_txt.text = "PERTANYAAN KE-"+i;
soal_txt.text = faq["Pertanyaan"+i]; ja_txt.text = faq["a"+i];
jb_txt.text = faq["b"+i];
jc_txt.text = faq["c"+i];
jd_txt.text = faq["d"+i];
jawaban =faq["benar"+i];
} else {
gotoAndStop(3);
skor_txt.text = score+"";
teks_txt.text = "Score akhir kamu :";
}
}
function cekJawaban(val) {
alert_mc.visible = true;
if (val != jawaban) {
alert_mc.alert_txt.text = "jawaban kamu salah, score anda berkurang 50 points";
score = score-50;
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok);
function btnok(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
} else {
score = score+100;
alert_mc.alert_txt.text = "jawaban kamu benar, score anda bertambah 100 points";
alert_mc.ok_btn.addEventListener(MouseEvent.CLICK,btnok2);
function btnok2(ev:MouseEvent):void
{
nextQst = i+1;
alert_mc.visible = false;
}
trace(score);
}
}
Error #1069:
Property Pertanyaan0 not found on String and there is no default value.
at revisi_fla::Symbol5_68/onComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()

Unity3D Instantiate works when not all conditions are met

This script should spawn object after clicking on other object which is closer than hitRange and has tag "Block". The problem is that it always spawns new object after pushing LMB, also when needed conditions weren't met.
#pragma strict
var blockName : String;
private static var blockToPlace : Rigidbody;
var hitRange : float;
private var hit : RaycastHit;
var blockLayer : int = 8;
private var hitBlock : boolean;
function Update(){
if(Input.GetMouseButtonDown(0)){
blockToPlace = EditorUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath("Assets/Models/Blocks/"+blockName+".prefab", Rigidbody)) as Rigidbody;
hitBlock = Physics.Raycast(transform.position, transform.forward, hit, Mathf.Infinity, blockLayer);
if(hitBlock == true){
if(hit.collider.tag == "Block"){
if(hit.distance < hitRange){
var block : Rigidbody;
block = Instantiate(blockToPlace,hit.normal+hit.transform.position,Quaternion.identity) as Rigidbody;
hitBlock = false;
}
}
}
}
}
I had a hard time with the same problem myself. Layers arn't exactly integers but rather bitshifts.
Watch this very nice video on layermasks: www.youtube.com/watch?v=n8mAjwn-MB8
var blockLayer : int = 8;
should be
var blockLayer : int = 1 << 8;

as3 socket with multi thread or background process in as3 socket

my project using flex mobile 4.5 using socket .. receive huge data stream..
and ui application like hang... in minute before all process data complete
and how to do with multi thread in socket in as3 ? any axamples ?
any trick? to make background process
bellow my code
private var workQueue:Array = new Array();
/**************** VARIABLES ************************/
[Bindable]public var defauldSocketIP:String ="119.99.67.168";
[Bindable]public var defauldPort:Number = 9090;
[Bindable]public var heartbeatTime:Number = 1000 * 60;
[Bindable]public var limitLivetrade:Number = 30;
[Bindable]public var sessionid:String;
[Bindable]public var userid:String;
[Bindable]public var password:String;
[Bindable]public var msgdata:String;
[Bindable]public var busyIndicator:Boolean = false;
[Bindable]public var livetradeData:ArrayCollection = new ArrayCollection();
[Bindable]public var IndicesSectoralData:ArrayCollection = new ArrayCollection();
[Bindable]public var topGainerBrokerData:ArrayCollection = new ArrayCollection();
[Bindable]public var brokerData:ArrayCollection = new ArrayCollection();
[Bindable]public var stockData:ArrayCollection = new ArrayCollection();
[Bindable]public var marketChartData:ArrayCollection = new ArrayCollection();
/* best Quote */
[Bindable]public var bestQuoteDataA:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteDataB:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteBID:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteOFFER:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteTFREQ:ArrayCollection = new ArrayCollection();
[Bindable]public var stockSummarayData:ArrayCollection = new ArrayCollection();
/* end of best Quote */
[Bindable]public var tempDataSocket:ByteArray = new ByteArray();
[Bindable]public var sTemp:int = new int();
[Bindable]public var db:ArrayCollection = new ArrayCollection();
[Bindable]public var curentCode:String;//current code for unscribe
/**************** Socket ********************/
private var buffer:ByteArray = new ByteArray();
public var _data:ByteArray;
[Bindable]public var websocketData:String;
[Bindable]public var isLogin:Boolean = false;
public var flipTrans:FlipViewTransition = new FlipViewTransition();
\
/* socket connection */
public var socket : Socket;
public function init() : void {
//navigator.defaultPushTransition = new FlipViewTransition();
socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onSocketClose);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onSEC_ERRORError );
/****************** INTERVAL FOR PING SERVER *************/
var myInterval:uint = setInterval (heartbeat, heartbeatTime);
//clearInterval(myInterval);
if(isLogin){
flipTrans.duration = 1000;
flipTrans.mode = FlipViewTransitionMode.CARD;
flipTrans.direction = ViewTransitionDirection.RIGHT;
mainview.pushView(MainView,null,null,flipTrans);
}
/****************** Database setup *************/
initDB();
if(db.length == 0){ createDefauldConfig(); }
}
/**************** menus ********************/
/**************** alert information box *********************/
protected function alertSoketError():void
{
Alert.show(this, Alert.IC_INFO, "Information", "Sorry cannot connect to server please contact administrator.");
}
/**************** inquotes database ********************/
public var sqlConnection:SQLConnection;
public function onSEC_ERRORError( errorEvent:SecurityErrorEvent ):void
{
busyIndicator = false;
isLogin = false;
mainview.pushView(login);
trace( "onSEC_ERRORError: " + errorEvent );
alertSoketError();
}
public function onSocketClose(e:Event,reconect:Boolean = true):void{ resetData();
socket.close();
mainview.pushView(login);
trace("socket Closed");
if(reconect){
reconnect();
}
}
public function onIOError( errorEvent:IOErrorEvent ):void
{
busyIndicator = false;
isLogin = false;
mainview.pushView(login);
trace( "IOError: " + errorEvent.text );
alertSoketError();
}
public function onConnect(event : Event) : void {
trace("login|"+userid+"|"+(MD5.hash(password)));
sendData("login|"+userid+"|"+(MD5.hash(password)));
}
public function getFormattedTime(t:int):String
{
var s:String = new String();
var hour:String = t.toString().substr(0,2);
var minute:String = t.toString().substr(2,2);
var scn:String = t.toString().substr(4,5);
return s =hour+":"+minute+":"+scn;
}
public function checkTipe(data:String):void{
var split:Array = spliter.doSplit(data,"|");
/*Login */
if(split[0]=="login" && split[1]=="ok" && isLogin == false){
trace("split[0]"+split[0]+"-split[1]"+split[1]+"isLogin =="+isLogin);
sessionid = new String();
sessionid = split[2];
isLogin = true;
flipTrans.duration = 1000;
flipTrans.mode = FlipViewTransitionMode.CARD;
flipTrans.direction = ViewTransitionDirection.RIGHT;
mainview.pushView(MainView,null,null,flipTrans);
sendData("subscribe|"+sessionid+"|4|0");
sendData("subscribe|"+sessionid+"|3|0");
sendData("subscribe|"+sessionid+"|5|0");
}
/*Login fail*/
if(split[0]=="login" && split[1]!="ok"){
sessionid = new String();
Alert.show(this, Alert.IC_INFO, "Login", "Sorry Fail.. check your user name or password");
}
/*live trade */
if(split[1]=="2"){
curentCode = "2";
var change:Number = split[17] == 0 ? 0 : split[6] - split[17];
var obj:Object = new Object();
obj.header = split[0];
obj.type = split[1];
obj.seqno = split[2];
obj.time = FormatTime.getFormattedTime(split[3]);
obj.stock = split[4];
obj.board = split[5];
obj.last = split[6];
obj.lot = split[7];
obj.buyer = split[8];
obj.buy = split[9];
obj.seller = split[10];
obj.sell = split[11];
obj.bestbid = split[12];
obj.bestbidlot = split[13];
obj.bestoffer = split[14];
obj.bestofferlot = split[15];
obj.tradeno = split[16];
obj.previous = split[17];
obj.change = change;
obj.percent = Number((change * 100 ) / split[17]).toFixed(1);
if(livetradeData.length < limitLivetrade){
livetradeData.addItem(obj);
}else{
livetradeData.removeItemAt(livetradeData.length-1);
livetradeData.addItemAt(obj,0);
}
livetradeData.refresh();
}
if(split[1]=="6"){
curentCode = "6" ;
IndicesSectoralData = IndicesSectoral.setIndicesSectoral(split,IndicesSectoralData);
IndicesSectoralData.refresh();
}
if(split[1]=="TSBB"){
curentCode = "TSBB";
var obj:Object = new Object();
obj.header = split[0];
obj.type = split[1];
obj.seqno = split[2];
obj.min1 = split[3];
obj.min2 = split[4];
obj.BrokerID = split[5];
obj.min3 = split[6];
obj.BuyAvg = split[7];
obj.SellAvg = split[8];
obj.BuyVol = split[9];
obj.BuyVal = formater.formatMoneyUnit(Number(split[10]));
obj.BuyFreq = split[11];
obj.SellVol = split[12];
obj.SellVal = formater.formatMoneyUnit(split[13]);
obj.SellFreq = formater.formatMoneyUnit(split[14]);
obj.ValNet = formater.formatMoneyUnit((Number(split[10]) -
Number(split[13])));
obj.TotalVal = formater.formatMoneyUnit((Number(split[10]) +
Number(split[13])));
obj.TotalVol = formater.formatMoneyUnit((Number(split[9]) +
Number(split[12])));
obj.FreqTotal = formater.formatMoneyUnit((Number(split[11]) +
Number(split[14])));
/*header|type|seqno|-|-|BrokerID|-|BuyAvg|SellAvg|BuyVol|BuyVal|BuyFreq|SellVol|SellVal|SellFreq
ValNet = BuyVal - SellVal
TotalVal = BuyVal + SellVal
TotalVol = BuyVol + SellVol
FreqTotal = BuyFreq + SellFreq
Diurut Berdasarkan TotalVal*/
var brokerIndex:int = find.findIndex(brokerData,"BrokerID", split[5]);
if(brokerIndex != -1){
obj.BrokerName = brokerData.getItemAt(brokerIndex).BrokerName;
}
var idx:int = find.findIndex(topGainerBrokerData,"BrokerID", split[5]);
//trace("BrokerID:"+idx+"arr[5]"+arr[5]);
if(idx == -1){
topGainerBrokerData.addItem(obj);
}else{
topGainerBrokerData.removeItemAt(idx);
topGainerBrokerData.addItemAt(obj,idx);
}
ArrayCollection. */
//topGainerBrokerData.sort = numericDataSort;
topGainerBrokerData.refresh();
}
/*broker */
if(split[1]=="4"){
curentCode = "4";
brokerData = Broker.setBroker(split,brokerData);
brokerData.refresh();
}
/*Stock */
if(split[1]=="3"){
curentCode = "3";
var objStock:Object = new Object();
objStock.header = split[0];
objStock.type = split[1];
objStock.seqno = split[2];
objStock.stockcode = split[3];
objStock.stockname = split[4];
objStock.status = split[5];
objStock.stocktype = split[6];
objStock.sector = split[7];
objStock.ipoprice = split[8];
objStock.baseprice = split[9];
objStock.listedshares = split[10];
objStock.tradelistedshares = split[11];
objStock.shareperlot = split[12];
var idStock:int = find.findIndex(stockData,"stockcode", split[3]);
//trace("BrokerID:"+idx+"arr[5]"+arr[5]);
if(idStock == -1){
stockData.addItem(objStock);
}else{
stockData.removeItemAt(idStock);
stockData.addItemAt(objStock,idStock);
}
}
if(split[1]=="1"){
curentCode = "1" ;
trace("best Quote A:"+data+"\n");
/* best quote bid */
var XB:Array = spliter.doSplit(data,"<");
var bLotBid:String = XB[1].toString().substring(1,XB[1].toString().indexOf("]")-1);
trace("bLotBid:"+bLotBid);
if(bLotBid != ""){
bLotBid = bLotBid.substring(1,bLotBid.length);
var bLotBidArr:Array = spliter.doSplit(bLotBid,">");
var bInt:int;
for(bInt = 0; bInt < 10;bInt++){
if(bLotBidArr[bInt] != undefined){
trace("dipotong :"+bLotBidArr[bInt]);
var bBidDAT:Array = spliter.doSplit(bLotBidArr[bInt],"|");
var obLotBid:Object = new Object();
obLotBid.freq = formater.formatNumber(bBidDAT[0]);
obLotBid.lot = formater.formatNumber(bBidDAT[1]);
obLotBid.bid = formater.formatNumber(bBidDAT[2]);
bestQuoteBID.addItem(obLotBid);
}
}
}
/* best quote bid */
/* offer */
var bOFF:String =
XB[1].toString().substring(XB[1].toString().indexOf("O[")+2,XB[1].toString().indexOf("]L"));
trace("bOFF:"+bOFF);
var boffArr:Array = spliter.doSplit(bOFF,">");
var bIof:int;
for(bIof = 0; bIof < 10;bIof++){
if(boffArr[bIof] != undefined && boffArr[bIof] != ""){
trace("dipotong offer :"+boffArr[bIof]);
var boofDAT:Array = spliter.doSplit(boffArr[bIof],"|");
var obLotBidOFF:Object = new Object();
obLotBidOFF.offer = formater.formatNumber(boofDAT[0]);
obLotBidOFF.lot = formater.formatNumber(boofDAT[1]);
obLotBidOFF.o = formater.formatNumber(boofDAT[2]);
bestQuoteOFFER.addItem(obLotBidOFF);
}
}
}
// best Quote B //
if(split[1]=="TP"){
curentCode = "TP";
trace("best Quote TP:"+data+"\n");
//header|type|seqno|stock|board|price|T.Lot|T.Freq
var objTp:Object = new Object();
objTp.header = split[0];
objTp.type = split[1];
objTp.seqno = split[2];
objTp.stock = split[3];
objTp.board = split[4];
objTp.price = formater.formatNumber(split[5]);
objTp.Tlot = formater.formatNumber(split[6]);
objTp.Tfreq = formater.formatNumber(split[7]);
bestQuoteTFREQ.addItem(objTp);
}
/* stock summary */
if(split[1]=="5"){
//curentCode = "5" ;
var objStcSum:Object = new Object();
objStcSum.header = split[0];
objStcSum.type = split[1];
objStcSum.seqno = split[2];
objStcSum.code = split[3];
objStcSum.board = split[4];
objStcSum.remarks = split[5];
objStcSum.previous = split[6];
objStcSum.highest = split[7];
objStcSum.lowest = split[8];
objStcSum.closing = split[9];
objStcSum.change = split[10];
objStcSum.tradedvolume = split[11];
objStcSum.tradedvalue = split[12];
objStcSum.tradedfrequency = split[13];
objStcSum.individualindices = split[14];
objStcSum.foreigner = split[15];
objStcSum.opening = split[16];
objStcSum.bestbid = split[17];
objStcSum.bestbidvolume = split[18];
objStcSum.bestoffer = split[19];
objStcSum.bestoffervolume = split[20];
stockSummarayData.addItem(objStcSum);
var idStockSum:int = find.findIndex(stockSummarayData,"code", split[3]);
if(idStockSum == -1){
stockSummarayData.addItem(objStcSum);
}else{
stockSummarayData.removeItemAt(idStockSum);
stockSummarayData.addItemAt(objStcSum,idStock);
}
}
/* market chart */
//trace("COMPOSITE-->"+split[1]);
if(split[0]=="CHI" && split[1]=="COMPOSITE"){
curentCode = "COMPOSITE";
//trace("split[1]:"+split[1]+"split[2]:"+split[2]+"split[3]:"+split[3]+"split[4]:"+split[4]);
var mrc:Array = spliter.doSplit(split.toString(),"\n");
if(split[2]!= null){
var o:int;
for(o = 0;o < (mrc.length -1);o++){
var dtmrc:Array = spliter.doSplit(mrc[o],",");
var objMcht:Object = new Object();
if(o == 0){
objMcht.time = FormatTime.getFormattedTime(dtmrc[2]);
objMcht.timeUnformat = dtmrc[2];
objMcht.type = dtmrc[3];
objMcht.value = dtmrc[4];
trace("mrc[o]"+mrc[o]+"== dtmrc:"+dtmrc[0]);
trace("dtmrc[2]"+dtmrc[2]);
trace("MARKET CHART time 0-->"+FormatTime.getFormattedTime(dtmrc[2]));
}else{
objMcht.time = FormatTime.getFormattedTime(dtmrc[0]);
objMcht.timeUnformat = dtmrc[0];
objMcht.type = dtmrc[1];
objMcht.value = dtmrc[2];
//trace("dtmrc[0]"+dtmrc[0]);
//trace("MARKET CHART time1-->"+FormatTime.getFormattedTime(dtmrc[0]))+"-->value-->"+dtmrc[2];
}
marketChartData.addItem(objMcht);
}
//time|type|value
}
marketChartData.refresh();
}
}
public function onSocketData(event : ProgressEvent) : void {
busyIndicator = true;
var msgdataTemp:String = new String();
var n:int = socket.bytesAvailable;
var bArray:ByteArray = new ByteArray();
try{
//trace("n "+n.toString());
while(n > 0){
var p:int = socket.bytesAvailable;
var s:int = new int();
if(sTemp == 0){
if(p > 0)
p = socket.bytesAvailable;
try{
s = socket.readInt();//total
}catch(e:EOFError){
trace("err :"+e);
break;
}
p = socket.bytesAvailable;
//trace("bArray"+bArray.toString()+" s:"+s.toString()+" "+p);
if(s > p){
var bytex:ByteArray = new ByteArray();
socket.readBytes(bytex,0,p);
tempDataSocket.writeBytes(bytex,0,bytex.length);
sTemp = s;
break;
}
socket.readBytes(bArray,0,s);
bArray.uncompress(CompressionAlgorithm.ZLIB);
checkTipe(bArray.toString());
n = n-( 4+ s);
}else{
if(sTemp > p){
//bArray.writeBytes(tempDataSocket,0,bArray.length);
socket.readBytes(bArray,0,p);
tempDataSocket.writeBytes(bArray,0,bArray.length);
// trace("sTemp > p sTemp :"+sTemp+" S :"+s+" p:"+p+" n:"+n+" "+tempDataSocket.length);
sTemp = sTemp +s;
if(sTemp == tempDataSocket.length){
tempDataSocket.uncompress(CompressionAlgorithm.ZLIB);
checkTipe(tempDataSocket.toString());
}
break;
}
//trace("sTemp :"+sTemp+" S :"+s+" p:"+p+" n:"+n+" tempDataSocket :"+tempDataSocket.length+" bArray.length:"+bArray.length);
var bnew:ByteArray = new ByteArray();
if(socket.bytesAvailable > 0){
socket.readBytes(bArray,0,(sTemp - tempDataSocket.length));
}
//tempDataSocket.writeBytes(bArray,tempDataSocket.length,bArray.length);
//bnew.writeBytes(bArray,sTemp
bnew.writeBytes(tempDataSocket,0,tempDataSocket.length);
bnew.writeBytes(bArray,0,bArray.length);
bnew.uncompress(CompressionAlgorithm.ZLIB);
//trace("bnew:"+bnew.toString());
checkTipe(bnew.toString());
tempDataSocket = new ByteArray();
n = socket.bytesAvailable;
sTemp = 0;
}
p = socket.bytesAvailable;
if(p>0){
}
}
}catch(ev:Error){
trace("socket_error:"+ev.getStackTrace());
}finally{
}
}
public function resetData():void{
sessionid = "";
msgdata = "";
busyIndicator = false;
livetradeData = new ArrayCollection();
IndicesSectoralData = new ArrayCollection();
topGainerBrokerData = new ArrayCollection();
brokerData = new ArrayCollection();
stockData = new ArrayCollection();
marketChartData = new ArrayCollection();
bestQuoteDataA = new ArrayCollection();
bestQuoteDataB = new ArrayCollection();
bestQuoteBID = new ArrayCollection();
bestQuoteOFFER = new ArrayCollection();
bestQuoteTFREQ = new ArrayCollection();
stockSummarayData = new ArrayCollection();
tempDataSocket = new ByteArray();
sTemp = new int();
curentCode = "";//current code for unscribe
buffer = new ByteArray();
_data = new ByteArray();
websocketData = "";
isLogin = false;
}
public function trim( s:String ):String
{
return s.replace( /^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2" );
}
private function removeBufferBefore(pos:int):void {
if (pos == 0) return;
var nextBuffer:ByteArray = new ByteArray();
buffer.position = pos;
buffer.readBytes(nextBuffer);
buffer = nextBuffer;
}
public function unSubscribe():void{
if(curentCode != null && sessionid != null && curentCode != ""){
try{
socket.writeMultiByte("unsubscribe|"+sessionid+"|"+curentCode,"iso-8859-1");
socket.writeByte(0xff);
socket.flush();
}catch(e:flash.events.ErrorEvent){
Alert.show(this, Alert.IC_INFO, "Sorry..", e.text);
}
}
}
public function sendData(data:String):void{
busyIndicator = true;
unSubscribe();
socket.writeMultiByte(data,"iso-8859-1");
socket.writeByte(0xff);
socket.flush();
trace("sendData:"+data);
}
public function connect(useridx:String,passwordx:String) : void {
busyIndicator = true;
userid = useridx;
password = passwordx;
trace("userid:"+userid);
trace("password:"+password);
socket.connect(db.getItemAt(0).defauldIpAdress, db.getItemAt(0).defauldPort);
//threadedSocket();
}
]]>
</fx:Script>
<s:ViewNavigator label="Main" backgroundColor="0x000" id="mainview" width="100%" height="100%"
firstView="views.login" icon="#Embed('assets/home.png')"/>
<s:ViewNavigator label="Menu" backgroundColor="0x000" width="100%" height="100%" firstView="views.MenuView"
icon="#Embed('assets/menu.png')"/>
<s:ViewNavigator label="about" backgroundColor="0x000" width="100%" height="100%" firstView="views.aboutView"
icon="#Embed('assets/info.png')"/>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
<!--<mx:NumberFormatter
decimalSeparatorFrom="."
decimalSeparatorTo="."
precision="-1"
rounding="none|up|down|nearest"
thousandsSeparatorFrom=","
thousandsSeparatorTo=","
useNegativeSign="true|false"
useThousandsSeparator="true|false"/>-->
<mx:NumberFormatter id="fortmar1" precision="6"
rounding="none"
decimalSeparatorFrom="."
decimalSeparatorTo="."
thousandsSeparatorTo=","
thousandsSeparatorFrom=","
useThousandsSeparator="true"
useNegativeSign="true"
/>
</fx:Declarations>
</s:TabbedViewNavigatorApplication>
If you are stuck with an old version of the flash player, you need to search google for "Green Threads in AS3".
If you are using a newer version of the player, or Adobe AIR for desktop and devices, multithreading, via "actionscript workers", is available.

Resources