我从发送器收到周期性信号(每分钟节拍) ,现在想在一段时间内调用方法,例如发送 1/1、1/2、1/4、1/8、1/16。 . 笔记。
我的解决方案是创建一个线程,做一个忙碌的等待,然后执行这些方法。这里的问题是监听信号、处理信号并将其发回会产生几毫秒的延迟(取决于系统)。
所以现在我想确定传入信号和线程周期信号之间的延迟,如果延迟是!= 0,则停止当前线程并在“bpm - delay”毫秒后启动一个新线程。如何才能做到这一点 ?
插图:
发射机信号:|----|----|----|----|
******跑步者信号:|----|----|----|----|
将跑步者信号延迟“onePeriod - delay”毫秒:
发射机信号:|----|----|----|----|
***"转轮信号:**** |----|----|----|----|
两个信号现在同步。
public class Quantiser implements Receiver{
private int[] bpmsInMillis = new int[4];
private int bpmInMillis=0;
private double smallestNote = 1;
private long period=0;
private long fire=0;
private long prevTimeStamp=0;
private Runnable runny = new Runnable() {
@Override
public void run() {
while(true){
fire = System.nanoTime() + period;
while(System.nanoTime() < fire){} // busy wait
// Call some methods here.
}
}
};
private Thread thread = new Thread(runny);
@Override
public void send(MidiMessage message, long timeStamp) {
// Calculate average bpm
for(int i=0; i<bpmsInMillis.length-1;i++)
bpmsInMillis[i] = bpmsInMillis[i+1];
bpmsInMillis[bpmsInMillis.length-1] = (int) ((timeStamp - prevTimeStamp) / 1000);
bpmInMillis = arithmeticMean(bpmsInMillis);
prevTimeStamp = timeStamp;
period = (long) (bpmInMillis * smallestNote * 1000000);
if(!thread.isAlive()) {
thread.start();
}
/*
else{
Calculate delay between signal and thread-signal.
if(delay != 0){
Delay new thread by "bpm - delay" milliseconds.
Stop old thread.
Start new thread.
}
*/
}
@Override
public void close() {
}