How to create an actionscript Object in Haxe - object

I am creating an actionscript video player in Haxe and to avoid the asyncError I am trying to create a custom Object. How do I do this is Haxe?
The client property specifies the object on which callback methods are invoked. The default object is the NetStream object being created. If you set the client property to another object, callback methods will be invoked on that other object.
Here is my code.
public function new()
{
super();
trace("video");
//initialize net stream
nc = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
buffer_time = 2;
ns.bufferTime = buffer_time;
//Add video to stage
myVideo = new flash.media.Video(640, 360);
addChild(myVideo);
//Add callback method for listeing on NetStream meta data
client = new Dynamic();
ns.client = client;
client.onMetaData = metaDataHandler;
}
public function playVideo(url:String)
{
urlName = new String(url);
myVideo.attachNetStream(ns);
ns.play(urlName);
ns.addEventListener(NetStatusEvent.NET_STATUS, netstat);
}
function netstat(stats:NetStatusEvent)
{
trace(stats.info.code);
}
function metaDataHandler(infoObject:Dynamic)
{
myVideo.width = infoObject.width;
myVideo.height = infoObject.height;
}

You should probably do:
client : Dynamic = {};

Forget the client object; it isn't necessary for playing FLVs or for handling async errors. For that, just add a listener to the NetStream for AsyncErrorEvent.ASYNC_ERROR.
I suggest you add a listener to the NetConnection and the NetStream for NetStatusEvent.NET_STATUS, and then trace out the event.info.code value within the listener.
You should first see the string "NetConnection.Connect.Success" coming from the NetConnection; when you play your video through the NetStream, you should see "NetStream.Play.StreamNotFound" if there's a problem loading the FLV. Otherwise you should see "NetStream.Play.Start".
Unless you're progressively streaming your FLV, you may not see any video playing until the file has finished loading. If the movie file is long, this may explain why your program is running without errors but isn't playing the movie. There are small test FLV files available online that you might wish to use while you track the problem down.
(ActionScript's FLV playback API is bizarre and haXe's documentation is rudimentary, so you're rightfully frustrated.)

This maybe useful... http://code.google.com/p/zpartan/source/browse/zpartan/media/
You can see it being used
http://code.google.com/p/jigsawx/

Related

How to pass information into Unreal Engine from outside source

The Problem:
I want a high quality visualization of a simulation that I've built and runs on another application. Unreal Engine 4 has models that work, and renders nicely enough to fill my needs. The only problem, is I need to tell a running instance of an Unreal Engine project some of the information that my simulation is creating, like moving objects.
Potential solutions:
rpc plugin?
I'm reasonably familiar with grpc, and my simulation is set up so send and receive grpc messages, but I don't know how to implement grpc through unreal_engine. A couple others on the interweb have written rpc plugins, which might work for my needs. For example...
https://github.com/PaddleCreekGames/Proto3RPC_UE4
However, no idea how to take that pile of work done and actually use what I want. Needless to say, the documentation of that specific project is unfriendly to a user who didn't write it.
Something else?
If you have any ideas, or if you've historically passed information to unreal engine a specific way, any pointers in the right direction/code snippets/links to stuff I may have missed would be greatly appreciated.
I had the same question with theodox,
if the input doesn't have to happen instantly/in real-time.
You may for example update a parameter file for you simulation and read the parameters in your unreal engine application.
Here is an example to create the readFile bluemix function to read and parse an external JSON file:
in /Source/[Project name]/MyBlueprintFunctionLibrary.h, define output struct and function header
USTRUCT(BlueprintType)
struct FResultStruct
{
GENERATED_USTRUCT_BODY()
UPROPERTY(EditAnywhere,BlueprintReadWrite,Category = "Result Struct")
float fieldname1;
UPROPERTY(EditAnywhere,BlueprintReadWrite,Category = "Result Struct")
FString fieldname2;
//Constructor
FResultStruct()
{
fieldname1 = 0;
fieldname2 = "string";
}
};
UCLASS()
class EXPERIMENTALPROJECT_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "MyBPLibrary")
static FResultStruct ReadFile(FString fileName);
};
in /Source/[Project name]/MyBlueprintFunctionLibrary.cpp implement your parameter file parser, for example:
// Read the results file
FResultStruct UMyBlueprintFunctionLibrary::ReadFile(FString fileName)
{
FString saveFilePath = FPaths::ConvertRelativePathToFull(FPaths::GameDir());
fileName = saveFilePath + fileName;
FResultStruct Result;
FString jsonString;
FFileHelper::LoadFileToString(jsonString, *fileName);
TSharedPtr<FJsonObject> JsonParsed;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(jsonString);
if (FJsonSerializer::Deserialize(JsonReader, JsonParsed))
{
Result.fieldname1 = JsonParsed->GetNumberField("fieldname1");
Result.fieldname2 = JsonParsed->GetStringField("fieldname2");
}
return Result;
}
And in your unreal engine blueprint you can call this file reading function and use its parsed content in your application:
example
If you need live input, you may need to create HUD in UE4 and create input fields for all your parameters, that's more labor intensive imo.

CSCore - Play audio from a FileStream or MemoryStream

Using CSCore, how can I play WMA or MP3 from a FileStream or MemoryStream (unlike using a method that take a string for a file path or url).
As the GetCodec(Stream stream, object key)-overload of the CodecFactory-class is internal, you could simply perform the same steps manually and directly choose your decoder. Acutally, CodeFactory is just a helper class for determining the decoders automatically, so if you already know about your codec, you can do this yourself.
Internally, when passing a file path, CSCore checks the file extension and then opens up a FileStream (using File.OpenRead) that is handled over to the chosen decoder.
All you need to do, is using the specific decoder for your codec.
For MP3, you could use the DmoMP3Decoder which inherits from DmoStream that implements the IWaveSource-interface you need to handle over as sound source.
Here is an adjusted sample from the docs on Codeplex:
public void PlayASound(Stream stream)
{
//Contains the sound to play
using (IWaveSource soundSource = GetSoundSource(stream))
{
//SoundOut implementation which plays the sound
using (ISoundOut soundOut = GetSoundOut())
{
//Tell the SoundOut which sound it has to play
soundOut.Initialize(soundSource);
//Play the sound
soundOut.Play();
Thread.Sleep(2000);
//Stop the playback
soundOut.Stop();
}
}
}
private ISoundOut GetSoundOut()
{
if (WasapiOut.IsSupportedOnCurrentPlatform)
return new WasapiOut();
else
return new DirectSoundOut();
}
private IWaveSource GetSoundSource(Stream stream)
{
// Instead of using the CodecFactory as helper, you specify the decoder directly:
return new DmoMp3Decoder(stream);
}
For WMA, you can use the WmaDecoder.
You should check the implementation of the different decoders: https://github.com/filoe/cscore/blob/master/CSCore/Codecs/CodecFactory.cs#L30
Make sure, that no exceptions are thrown and handle them with the usage of another decoder (Mp3MediafoundationDecoder) as in the linked source code. Also don't forget to dispose your stream in the end.

Flux - Isn't it a bad practice to include the dispatcher instance everywhere?

Note: My question is about the way of including/passing the dispatcher instance around, not about how the pattern is useful.
I am studying the Flux Architecture and I cannot get my head around the concept of the dispatcher (instance) potentially being included everywhere...
What if I want to trigger an Action from my Model Layer? It feels weird to me to include an instance of an object in my Model files... I feel like this is missing some injection pattern...
I have the impression that the exact PHP equivalent is something (that feels) horrible similar to:
<?php
$dispatcher = require '../dispatcher_instance.php';
class MyModel {
...
public function someMethod() {
...
$dispatcher->...
}
}
I think my question is not exactly only related to the Flux Architecture but more to the NodeJS "way of doing things"/practices in general.
TLDR:
No, it is not bad practice to pass around the instance of the dispatcher in your stores
All data stores should have a reference to the dispatcher
The invoking/consuming code (in React, this is usually the view) should only have references to the action-creators, not the dispatcher
Your code doesn't quite align with React because you are creating a public mutable function on your data store.
The ONLY way to communicate with a store in Flux is via message passing which always flows through the dispatcher.
For example:
var Dispatcher = require('MyAppDispatcher');
var ExampleActions = require('ExampleActions');
var _data = 10;
var ExampleStore = assign({}, EventEmitter.prototype, {
getData() {
return _data;
},
emitChange() {
this.emit('change');
},
dispatcherKey: Dispatcher.register(payload => {
var {action} = payload;
switch (action.type) {
case ACTIONS.ADD_1:
_data += 1;
ExampleStore.emitChange();
ExampleActions.doThatOtherThing();
break;
}
})
});
module.exports = ExampleStore;
By closing over _data instead of having a data property directly on the store, you can enforce the message passing rule. It's a private member.
Also important to note, although you can call Dispatcher.emit() directly, it's not a good idea.
There are two main reasons to go through the action-creators:
Consistency - This is how your views and other consuming code interacts with the stores
Easier Refactoring - If you ever remove the ADD_1 action from your app, this code will throw an exception rather than silently failing by sending a message that doesn't match any of the switch statements in any of the stores
Main Advantages to this Approach
Loose coupling - Adding and removing features is a breeze. Stores can respond to any event in the system with by adding one line of code.
Less complexity - One way data flow makes wrapping head around data flow a lot easier. Less interdependencies.
Easier debugging - You can debug every change in your system with a few lines of code.
debugging example:
var MyAppDispatcher = require('MyAppDispatcher');
MyAppDispatcher.register(payload => {
console.debug(payload);
});

How to remove a listener in chrome.webRequest API in dart?

Related to `chrome.webRequest.onBeforeRequest.removeListener`? -- How to stop a chrome web listener, I am trying to deregister a listener using dart:js
After invoking onBeforeRequest.callMethod('removeListener', [callback]); I notice that the listener is still being called. Furthermore, directly after adding a listener the hasListenerreturns false (even thought the listener is being registered).
var callback = (map) { /* some code */ };
var filter = new JsObject.jsify({"key": "value"});
var opt_extraInfoSpec = new JsObject.jsify(["extra opt"]);
// chrome.webRequest.onBeforeRequest.addListener
JsObject onBeforeRequest = context['chrome']['webRequest']['onBeforeRequest'];
onBeforeRequest.callMethod('addListener', [callback, filter, opt_extraInfoSpec]);
Logger.root.fine('main(): does callback exist: ${onBeforeRequest.callMethod('hasListener', [callback])}');
It seems to be necessary to follow 100% the dart:js recommendations how to use a dart Function in the javascript environment. I guess my problem was that the original dart dynamic function is wrapped automatically in a proxy. Hence the callMethod for addListener used a different proxy object then the callMethod for hasListener, even thought both of them were based on the same original dart object (i.e. callback).
The solution is to use the JsFunction and define the callback as following:
var callback = new JsFunction.withThis((that, map) { /* some code */ });

Correct usage of events in NodeJs - Concerning "this" context

I am designing a communication server in Node that handles incoming messages (sent by client1) and transfers them to someone else (client2), who answers the message and sends the answer back, via the server, to client1.
The communication happens via WebSockets, which implies an open connection from each client to the server.
Thus I implemented a ConnectionManager to which I can register any new connections when a new client comes online. Every connection gets assigned a messageQueue in which all incoming messages are cached before processing.
At the end of processing, I have a ServerTaskManager, who generates Output-Tasks for the server, telling him a message to send and a receiver to receive it.
This ServerTaskManager emits a Node-Event (inherits from EventEmitter) upon registering a new serverTask to which the server listens.
Now I would like my ConnectionManager to also listen to the event of the serverTaskManager, in order to make him push the next message in the messageQueue into processing.
Now the problem is, that I can catch the ServerTaskManager event within the ConnectionManager just fine, but, of course, the "this" within the listener is the ServerTaskManager, not the ConnectionManager. Thus calling any "this.someFunction()" functions that belong to the ConnectionManager won't work.
Here is some code:
/**
* ServerTaskManager - Constructor
* Implements Singleton pattern.
*/
function ServerTaskManager()
{
var __instance;
ServerTaskManager = function ServerTaskManager()
{
return __instance;
}
ServerTaskManager.prototype = this;
__instance = new ServerTaskManager();
__instance.constructor = ServerTaskManager;
return __instance;
}
util.inherits(ServerTaskManager, EventEmitter);
/**
* ConnectionManager - Constructor
* Also implements Singleton pattern.
*/
function ConnectionManager()
{
var __instance;
ConnectionManager = function ConnectionManager()
{
return __instance;
}
ConnectionManager.prototype = this;
__instance = new ConnectionManager();
__instance.constructor = ConnectionManager;
__instance.currentConnections = [];
// Listen for new serverInstructions on the serverTaskManager
serverTaskManager.on('newInstruction', function(messageObject, currentReceiver)
{
this.processNextMessage(currentReceiver);
});
return __instance;
}
util.inherits(ConnectionManager, EventEmitter);
Now when I run this and the "newInstructions" event is triggered by the serverTaskManager, node throws:
TypeError: Object #<ServerTaskManager> has no method 'processNextMessage'
Which is of course true. The function I want to call belongs to the ConnectionManager:
/**
* Starts processing the next message
*
* #param connectionId (int) - The ID of the connection, of which to process the next message.
*/
ConnectionManager.prototype.processNextMessage = function (connectionId)
{
// Some Code...
}
So obviously, when listening to the ServerTaskManager event, "this" within the listener is the ServerTaskManager. Now how do I call my ConnectionManager's function from within the listener?
I hope I am not completely misled by how events and listeners and/or prototypical extensions work (in Node). This project is by far the most advanced that I have worked on in JavaScript. Normally I am only coding PHP with a little bit of client side JS.
Thx in advance for any hints!
Worp
Like this.
serverTaskManager.on('newInstruction', function(messageObject, currentReceiver)
{
ConnectionManager.processNextMessage(currentReceiver);
});
Or like this.
serverTaskManager.on('newInstruction', function(messageObject, currentReceiver)
{
ConnectionManager().processNextMessage(currentReceiver);
});
PS: your question is unnecessarily long. When posting code, don't necessarily post your example. It is much easier to boil your code down to the simplest form that exhibits the behavior you are seeing. You'll get more quality responses this way.

Resources