Web audio - How to call a function based on current Time? - audio

I was wondering could you please help. I am using the web audio to play music for a certain amount of time. After around 90 seconds (depending on length of song), i want to call my loadAndPlay() function again to repeat play. The function will be called every 90 seconds or so.
I would like to use the same method to trigger effects at the same time, using Tuna.js
it seems that this will not work:
if (context.currentTime > 90*totalPlays)
{
loadAndPlay();
}
i have also tried using this method:
if (time > 90*totalPlays){
source.onended = function()
{
console.log("End. starting again");
loadAndPlay();
totalPlays++
}
time will usually be around 90 and 105. This works sometimes but not all the time unfortunately. I would like to steer away from 'source.onended' anyway as it is unreliable.
the same idea using effects, cueing a delay for 15 seconds
while (context.currentTime > 90 && context.currentTime < 105){
delay.wetLevel = 10
}
if anyone could point out where i'm going wrong that would be fantastic. thank you!

Related

Vote system to my discord bot with nodejs

I'm making a command .report #user that creates a simple poll with 2 buttons added "agree" and "disagree". After certain time i want the bot to register user if agree's is more than disagree.
How can i make my bot count the results of voting after 7 days and then based on this either register on DB an user or send "Report Voting Failed".
What I hope is to be able to store the expiration date of the voting and that on that date the voting stops working and the corresponding action is taken.
You can use setTimeout() for this. setTimeout() takes in two parameters. One, a function which holds your code that will be ran after the time has passed. Two, the amount of time in milliseconds to wait before executing your code.
Here is an example of how to use this.
console.log('1') // will console.log 1 instantly
setTimeout(() => {
console.log('2') // will console.log 2 after 1 second.
},
1000) // 1s = 1000ms
Furthermore, you can use buttons to accomplish the task of reporting. Check out the guide on buttons for more info. Once a button is pushed, see whether it is an Agree or Disagree then do what you must from there. After the seven days is up, make the buttons unable to press, or whatever you want.
You might want to employ a node.js module such as ms to convert 7d into ms. This could be useful as 7 days in milliseconds is 604,800,000. Using ms,
you could do
const sevenDays = ms('7d') // returns 604800000
and then pass that into your setTimeout() function.
like so:
setTimeout(() => {
console.log('The seven days has passed')
}, sevenDays)
Note however your bot will need to stay online for the duration of these 7 days, otherwise it will not run as it has forgotten that the setTimeout() function was used in an earlier instance.

skipping to specific currentTime with pixi-sound

I'm using pixi-sound.js and want to be able to skip to a specific point in the audio file. I've achieved this before using HTML5 audio by updating the currentTime, but I'm not sure where to access this with pixi-sound. There are at least two currentTime values, as well as 'progress', in the object, but changing those doesn't cause a skip.
var sound = PIXI.sound._sounds['track01'];
var currenttime = sound.media.context.audioContext.currentTime;
I would have thought this would be a common usage thing, but can't find any reference to it in the documents. Any ideas much appreciated.
In PixiJS Sound, you can hand over a options object as an argument for play method of an instance of Sound class. And the value of options.start is the "start time offset in seconds".
References: #pixi/sound v4.2.0 source, pixi-sound v3.0.5 source
In your code, if you want to play the sound from the point of 10 seconds offset, I think you can try like the following:
var sound = PIXI.sound._sounds['track01'];
sound.play({ start: 10 }); // play from 10 seconds offset

Why ( new Date() ).toString() is so slow in Node.js?

I am playing a bit with Node.js. I've just started writing something new and it stuck me that my simple "console" app takes quite long to respond. This app loads a 5MB json file, turns it into an object but all that still does not take a significant amount of time. My further search (in a quite short and simple code) led me to conclusion that this single line:
this.generated_on = ( new Date() ).toString();
takes around 2.5s to execute. Further investigation made me understand even less. I've modified it to:
this.generated_on = new Date();
this.generated_on = this.generated_on.toString();
(with console.timeLogs in between) and line with toString() was the one that took over 2 seconds to execute. Then, I've modified the code once again:
this.generated_on = new Date('2019-02-04 20:00:00');
this.generated_on = this.generated_on.toString();
and results were other way around. toString() took only 2ms while creating Date object took over 2s.
Why is it so slow? Why so different results? Any faster way to get formatted current time string? (I don't care much about execution time for this project as it works offline, still it bugs me).
I think your development environment is off or something. I cannot tell you why your machine is running the code in a slow manner. I cannot replicate the problem you were saying.
I tried to benchmark the code you have above.
https://repl.it/#act/HotpinkFearfulActiveserverpages
Go here and try clicking on Run button at the top.
Here's the result I am seeing
// Case Togehter:
// this.generated_on = ( new Date() ).toString();
// Case Separately:
// this.generated_on = new Date();
// this.generated_on = this.generated_on.toString();
Together x 332,222 ops/sec ±7.75% (44 runs sampled)
Separtely x 313,162 ops/sec ±8.48% (43 runs sampled)
332,222 ops/sec means an operation took 1/332,222 seconds on average.
I suggest you to use node.js builtin module 'Performance hooks'.
You can find documentation here: https://nodejs.org/dist/latest-v11.x/docs/api/perf_hooks.html#perf_hooks_performance_mark_name
Mark each process from top to bottom and then print the metrics (in milliseconds), you will figure out the actual issue

How do I count the number of users in my quiz bot?

I am using bot framework where I proactively start a quiz game every 24 hours. The code for this looks like
bot.beginDialog(user.address, '/runChallenge', args, (error) => {
if (error) {
// error ocurred while starting new conversation. Channel not supported?
console.log(JSON.stringify(error), user.address)
bot.send(new builder.Message()
.text("The rat nibbled the wires before we could start the game for you. Sorry about that :(")
.address(user.address));
}
})
A couple of questions
How do i count the number of players in the game?
I could make a global variable called players inside my bot.js file
and increment it by 1 each time the bot.dialog('/quiz') is called
inside its 1st waterfall step. Given the file is included once at
the beginning, once I increment it, I guess i ll have to reset it
back to 0 somewhere.
Or I could use a local variable inside the cron job function which
can pass another parameter called playersCount as args to the dialog
where it will be a local variable but I am not sure if this is the
right approach
Everytime, a person answers incorrectly, they are out of the
challenge. I would like to count how many people answered
incorrectly. What would be a good way to go about this?
I would also like to declare the results of the quiz after say
everyone is done with it, The maximum time taken by anyone and
everyone is 15 mins for the round. I am planning to use a setTimeout
after 15 mins of initiating the game since I already use a CronJob
every 23 hours to trigger the quiz. Any suggestions?

Phonegap Media getCurrentPosition is inaccurate and slow

I have been very disappointed to find that now that I am ready to migrate my html5 app onto phones using phonegap the ability to play audio is like perpetual motion. It is almost there, but not quite.
The answer for Androids (pre ice cream sandwich at least) is the Phonegap media api. According to everyone.
The problem is that I REALLY care about what the current time is while playing back my audio. On my Mac running Chrome I timed how long it takes to do:
pos=audio.currentTime
and it is less than a millisecond.
With the Phonegap media api I must call an asynchronous function, WAIT till it calls back and then I get the current media position. This takes anywhere from 5 to over 150 milliseconds. It is not consistent and it is distressingly slow.
It also begs the question: what time is it? If it takes 150ms to get the time, did I get the time at the beginning of those 150ms or the end? I really cant be sure that the time I got is really that close to the current time.
Its a good thing I am not still writing submarine navigation software, because with such a horrible source of time I would never be able to determine where I am.
I am now using the system clock to keep track of time, and using getCurrentPosition() to re-sync from time to time. However, I can still be off by over a hundred ms.
My question: Anyone got a better approach?
EDIT:
Looking at the code for Cordova:
/**
* Get current position of playback.
*
* #return position in msec or -1 if not playing
*/
public long getCurrentPosition() {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
int curPos = this.player.getCurrentPosition();
this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + curPos / 1000.0f + ");");
return curPos;
}
else {
return -1;
}
}
It looks to me like this should execute pretty fast...except for that call to sendJavascript(). I wonder if that is where the mysterious delay is originating?
For my purposes I don't need an onStatus event: I need to get the current position as quickly as I can. So I wonder if I can remove that line of code... I guess that would necessitate a change to the Cordova source itself. :(

Resources