How can you detect if ANY sounds are currently playing in soundJS? - audio

How can you detect if any sounds are playing in soundJS?
I have lots of sounds firing on and off sometimes legitimately over the top of each other. I need a way to find out if any sounds are playing at any given time
ie. something like
createjs.Sound.isPlaying()
or
createjs.Sound.status()

Nothing exists like this in SoundJS currently.
You can look it up yourself, but it involves digging into private members, which is not recommended, and could break content down the road. Here is a quick sample:
function countActiveSounds() {
var s = createjs.Sound.activePlugin,
count = 0;
for (var n in s._soundInstances) {
var inst = s._soundInstances[n];
for (var i=0, l=inst.length; i<l; i++) {
var p = inst[i];
if (p.playState == "playSucceeded") { count++; }
}
}
return count;
}
This involves reading the private _soundInstances hash, and checking if the sound state is "playSucceeded". Once it is complete, the state will changed to "playFinished".
Again, use this with caution :)
It might make sense to log a feature request to the SoundJS GitHub.

Related

How to decrypt in BlockChain?

I have been asked to use BlockChain for a web app I am building and I did not hear about it before, after searching some information about it, now I understand what it is about. So, basically it encrypts some data in blocks and in this way, the data is safe.
For instance, I have this code I took from internet:
const SHA256 = require('crypto-js/sha256')
class Block {
constructor(timestamp, data) {
this.index = 0;
this.timestamp = timestamp;
this.data = data;
this.previousHash = "0";
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + this.data + this.nonce).toString();
}
mineBlock(difficulty) {
}
}
class Blockchain{
constructor() {
this.chain = [this.createGenesis()];
}
createGenesis() {
return new Block(0, "01/01/2017", "Genesis block", "0")
}
latestBlock() {
return this.chain[this.chain.length - 1]
}
addBlock(newBlock){
newBlock.previousHash = this.latestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
checkValid() {
for(let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
let jsChain = new Blockchain();
jsChain.addBlock(new Block("12/25/2017", {amount: 5}));
jsChain.addBlock(new Block("12/26/2017", {amount: 10}));
And this is the result:
As you can see, we have encrypted "Genesis block" in blocks (if I am not wrong).
Ok so, what if I want to decrypt the data in order to get "Genesis block" back? Will this be possible?
I am new at this, so I find it a bit confusing... I understand what it is about but I do not know how I would implement it to my web app. My web app basically gets some information from the database, shows that information to the final user and the final user sends an email to a customer who will have to pay through a link.
Blockchains are not about encrypting data to keep it "safe"; they are about creating an auditable ledger of changes to some state that needs to be agreed by multiple parties. In the case of bitcoin, they represent the distribution of currency across different wallets, and record transactions which change that distribution.
Blockchains are a very specialized technology, and while there are a few situations where they are useful, there are also a lot people searching for problems to fit the solution. You're better off analysing your actual problems first, and then looking around for technologies that solve those problems.
In this case, your number one priority should be general security - if someone manages to run an UPDATE on your internal database, something has already gone very wrong. As part of "defence in depth", you might also want an audit trail of changes that have been made. That might mean picking a database technology that forms an append-only ledger, but unlike a traditional blockchain, you probably don't need that to be based on distributed consensus. And you might find that actually having a separately secured audit log that you can cross-check if anything suspicious happens is enough for the scenarios you're expecting.
Finally, if you do decide that a blockchain-based ledger solves a real problem you have, look for an existing implementation you can take advantage of, for the same reason you wouldn't try to write MySQL from scratch.

Node.js, For loop

in node.js I am using for loop on server.js but it is not working and cause error
var myEasyrtcApp = function(err, appObj) {
for (i = 0; i < 10; i++) {
appObj.createRoom("room" + i ,null,function(err, roomObj){});
};
}
Please advice how can I use for loop to call appObj.createRoom several time to open different conference room
Sorry, but you almost not give any information... Asuming the last function is a Callback you need to make a Recursive "Loop" something like:
http://pastebin.com/LrKqLgyV
And to use it you can do this:
http://pastebin.com/L1bZZis0
To learn more about this, just google "recursive functions". (I can't post more than 2 links XD)
Hope It works for you ;)

spotify models.Track object

is the spotify models.Track object restricted to non-local tracks only?
I've built a little spotify app that will calculate the total play time of some random assortment of tracks that are dropped into the sidebar, but it seems like the Track object doesn't get any information from local files.
Here's what I got so far:
models.application.observe(models.EVENT.LINKSCHANGED, function () {
totalTime = 0;
var links = models.application.links;
if (links.length) {
for (var i = 0; i < links.length; i++) {
var track = models.Track.fromURI(links[i], function(t) {
totalTime = totalTime + t.duration;
});
}
}
document.getElementById("time").innerHTML = secondsToString(Math.round(totalTime/1000)) ;
});
Everything is firing correctly and working great on spotify tracks, but the whole reason i wrote this little app was so that I could calculate the total time of some of my really long audiobook files. Anyone know of a solution?
Link to the documentation page.
If this is indeed the case, I think you've found a bug/oversight.
However, local file URIs look like this: spotify:local:Coldplay:Mylo+Xyloto:Paradise:277
That last parameter is the length of the track, in integral seconds. It's a hacky workaround, but you could parse the URI and use the figure from that instead of models.Track.

Caching requests to reduce processing (TPL?)

I'm currently trying to reduce the number of similar requests being processed in a business layer by:
Caching the requests a method receives
Performing the slow processing task (once for all similar requests)
Return the result to each requesting method calls
Things to note, are that:
The original method calls are not currently in a async BeginMethod() / EndMethod(IAsyncResult)
The requests arrive faster than the time it takes to generate the output
I'm trying to use TPL where possible, as I am currently trying to learn more about this library
eg. Improving the following
byte[] RequestSlowOperation(string operationParameter)
{
Perform slow task here...
}
Any thoughts?
Follow up:
class SomeClass
{
private int _threadCount;
public SomeClass(int threadCount)
{
_threadCount = threadCount;
int parameter = 0;
var taskFactory = Task<int>.Factory;
for (int i = 0; i < threadCount; i++)
{
int i1 = i;
taskFactory
.StartNew(() => RequestSlowOperation(parameter))
.ContinueWith(result => Console.WriteLine("Result {0} : {1}", result.Result, i1));
}
}
private int RequestSlowOperation(int parameter)
{
Lazy<int> result2;
var result = _cacheMap.GetOrAdd(parameter, new Lazy<int>(() => RequestSlowOperation2(parameter))).Value;
//_cacheMap.TryRemove(parameter, out result2); <<<<< Thought I could remove immediately, but this causes blobby behaviour
return result;
}
static ConcurrentDictionary<int, Lazy<int>> _cacheMap = new ConcurrentDictionary<int, Lazy<int>>();
private int RequestSlowOperation2(int parameter)
{
Console.WriteLine("Evaluating");
Thread.Sleep(100);
return parameter;
}
}
Here is a fast, safe and maintainable way to do this:
static var cacheMap = new ConcurrentDictionary<string, Lazy<byte[]>>();
byte[] RequestSlowOperation(string operationParameter)
{
return cacheMap.GetOrAdd(operationParameter, () => new Lazy<byte[]>(() => RequestSlowOperation2(operationParameter))).Value;
}
byte[] RequestSlowOperation2(string operationParameter)
{
Perform slow task here...
}
This will execute RequestSlowOperation2 at most once per key. Please be aware that the memory held by the dictionary will never be released.
The user delegate passed to the ConcurrentDictionary is not executed under lock, meaning that it could execute multiple times! My solution allows multiple lazies to be created but only one of them will ever be published and materialized.
Regarding locking: this solution will take locks, but it does not matter because the work items are far more expensive than the (few) lock operations.
Honestly, the use of TPL as a technology here is not really important, this is just a straight up concurrency problem. You're trying to protect access to a shared resource (the cached data) and, to do that, the only approach is to lock. Either that or, if the cache entry does not already exist, you could allow all incoming threads to generate it and then subsequent requesters benefit from the cached value once it's stored, but there's little value in that if the resource is slow/expensive to generate and cache.
Perhaps some more details will make it clear on exactly why you're trying to accomplish this without a lock. I'll happily to revise my answer if more detail makes it clearer what you're trying to do.

Can I allow for "breaks" in a for loop with node.js?

I have a massive for loop and I want to allow I/O to continue while I'm processing. Maybe every 10,000 or so iterations. Any way for me to allow for additional I/O this way?
A massive for loop is just you blocking the entire server.
You have two options, either put the for loop in a new thread, or make it asynchronous.
var data = [];
var next = function(i) {
// do thing with data [i];
process.nextTick(next.bind(this, i + 1));
};
process.nextTick(next.bind(this, 0));
I don't recommend the latter. Your just implementing naive time splicing which the OS level process scheduler can do better then you.
var exec = require("child_process").exec
var s = exec("node " + filename, function (err, stdout, stderr) {
stdout.on("data", function() {
// handle data
});
});
Alternatively use something like hook.io to manage processes for you.
Actually you probably want to aggressively redesign your codebase if you have a blocking for loop.
Maybe something like this to break your loop into chunks...
Instead of:
for (var i=0; i<len; i++) {
doSomething(i);
}
Something like:
var i = 0, limit;
while (i < len) {
limit = (i+10000);
if (limit > len)
limit = len;
process.nextTick(function(){
for (; i<limit; i++) {
doSomething(i);
}
});
}
}
The nextTick() call gives a chance for other events to get in there, but it still does most looping synchronously which (I'm guessing) will be a lot faster than creating a new event for every iteration. And obviously, you can experiment with the number (10,000) till you get the results you want.
In theory, you could also use setTimeout() rather than nextTick(), in case it turns out that giving other processes a somewhat bigger "time-slice" helps. That gives you one more variable (the timeout milliseconds) that you can use for tuning.

Resources