我正在使用TarsosDSP实时计算音高。它使用AudioDispatcher实现Runnable并通过handlePitch方法发布结果以在主线程中使用。
我正在使用SurfaceView在更新时绘制此值。 SurfaceView还需要另一个线程在画布上绘制。所以我有2个可运行的对象。我无法管理如何通过一个线程更新表面视图,同时从另一个线程(audiodispatcher)获取音高值。
我只想使用我在handlePitch()方法中获得的分值来更新我在surfaceview上的绘图。但我的应用冻结了。有什么想法吗?
在MainAcitivity.java(onCreate(...))
myView = (MySurfaceView) findViewById(R.id.myview);
int sr = 44100;//The sample rate
int bs = 2048;
AudioDispatcher d = AudioDispatcherFactory.fromDefaultMicrophone(sr,bs,0);
PitchDetectionHandler printPitch = new PitchDetectionHandler() {
@Override
public void handlePitch(final PitchDetectionResult pitchDetectionResult, AudioEvent audioEvent) {
final float p = pitchDetectionResult.getPitch();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (p != -1){
float cent = (float) (1200*Math.log(p/8.176)/Math.log(2)) % 12;
System.out.println(cent);
myView.setCent(cent);
}
}
});
}
};
PitchProcessor.PitchEstimationAlgorithm algo = PitchProcessor.PitchEstimationAlgorithm.YIN; //use YIN
AudioProcessor pitchEstimator = new PitchProcessor(algo, sr,bs,printPitch);
d.addAudioProcessor(pitchEstimator);
d.run();//starts the dispatching process
AudioProcessor p = new PitchProcessor(algo, sr, bs, printPitch);
d.addAudioProcessor(p);
new Thread(d,"Audio Dispatcher").start();
在SurfaceView.java中(下面的代码是从构造函数触发的)
myThread = new MyThread(this);
surfaceHolder = getHolder();
bmpIcon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
iconWidth = bmpIcon.getWidth();
iconHeight = bmpIcon.getHeight();
density = getResources().getDisplayMetrics().scaledDensity;
setLabelTextSize(Math.round(DEFAULT_LABEL_TEXT_SIZE_DP * density));
surfaceHolder.addCallback(new SurfaceHolder.Callback(){
@Override
public void surfaceCreated(SurfaceHolder holder) {
myThread.setRunning(true);
myThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
myThread.setRunning(false);
while (retry) {
try {
myThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}});
protected void drawSomething(Canvas canvas) {
updateCanvas(canvas, this.cent); //draws some lines depending on the cent value
}
public void setCent(double cent) {
if (this.cent > maxCent)
this.cent = maxCent;
this.cent = cent;
}
更新:
MyThread.java
public class MyThread extends Thread {
MySurfaceView myView;
private boolean running = false;
public MyThread(MySurfaceView view) {
myView = view;
}
public void setRunning(boolean run) {
running = run;
}
@Override
public void run() {
while(running){
Canvas canvas = myView.getHolder().lockCanvas();
if(canvas != null){
synchronized (myView.getHolder()) {
myView.drawSomething(canvas);
}
myView.getHolder().unlockCanvasAndPost(canvas);
}
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
如果我正确理解了您的问题,那么您有一个独立的事件源,它在自己的线程(PitchDetectionHandler
)和SurfaceView
上工作,您希望在事件发生时重新绘制自己的线程从源头来。如果是这种情况,那么我认为sleep(1000)
的整个想法是错误的。您应该跟踪实际事件并对它们做出反应而不是等待它们。似乎在Android上最简单的解决方案是使用HandlerThread
/ Looper
/ Handler
基础设施,如下所示:
请注意以下代码中的错误;不仅是我尝试过的天堂,但我甚至还没有编译它。
import android.graphics.Canvas;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.SurfaceHolder;
public class SurfacePitchDrawingHelper implements Handler.Callback, SurfaceHolder.Callback2 {
private static final int MSG_DRAW = 100;
private static final int MSG_FORCE_REDRAW = 101;
private final Object _lock = new Object();
private SurfaceHolder _surfaceHolder;
private HandlerThread _drawingThread;
private Handler _handler;
private float _lastDrawnCent;
private volatile float _lastCent;
private final boolean _processOnlyLast = true;
@Override
public void surfaceCreated(SurfaceHolder holder) {
synchronized (_lock) {
_surfaceHolder = holder;
_drawingThread = new HandlerThread("SurfaceDrawingThread") {
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
}
};
_drawingThread.start();
_handler = new Handler(_drawingThread.getLooper(), this); // <-- this is where bug was
_lastDrawnCent = Float.NaN;
//postForceRedraw(); // if needed
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
synchronized (_lock) {
// clean queue and kill looper
_handler.removeCallbacksAndMessages(null);
_drawingThread.getLooper().quit();
while (true) {
try {
_drawingThread.join();
break;
} catch (InterruptedException e) {
}
}
_handler = null;
_drawingThread = null;
_surfaceHolder = null;
}
}
@Override
public void surfaceRedrawNeeded(SurfaceHolder holder) {
postForceRedraw();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
synchronized (_lock) {
_surfaceHolder = holder;
}
postForceRedraw();
}
private void postForceRedraw() {
_handler.sendEmptyMessage(MSG_FORCE_REDRAW);
}
public void postRedraw(float cent) {
if (_processOnlyLast) {
_lastCent = cent;
_handler.sendEmptyMessage(MSG_DRAW);
} else {
Message message = _handler.obtainMessage(MSG_DRAW);
message.obj = Float.valueOf(cent);
_handler.sendMessage(message);
}
}
private void doRedraw(Canvas canvas, float cent) {
// put actual painting logic here
}
@Override
public boolean handleMessage(Message msg) {
float lastCent = _processOnlyLast ? _lastCent : ((Float) msg.obj).floatValue();
boolean shouldRedraw = (MSG_FORCE_REDRAW == msg.what)
|| ((MSG_DRAW == msg.what) && (_lastDrawnCent != lastCent));
if (shouldRedraw) {
Canvas canvas = null;
synchronized (_lock) {
if (_surfaceHolder != null)
canvas =_surfaceHolder.lockCanvas();
}
if (canvas != null) {
doRedraw(canvas, lastCent);
_surfaceHolder.unlockCanvasAndPost(canvas);
_lastDrawnCent = lastCent;
}
return true;
}
return false;
}
}
然后在您的活动课程中,您可以执行类似
的操作private SurfaceView surfaceView;
private SurfacePitchDrawingHelper surfacePitchDrawingHelper = new SurfacePitchDrawingHelper();
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.getHolder().addCallback(surfacePitchDrawingHelper);
int sr = 44100;//The sample rate
int bs = 2048;
AudioDispatcher d = AudioDispatcherFactory.fromDefaultMicrophone(sr, bs, 0);
PitchDetectionHandler printPitch = new PitchDetectionHandler() {
@Override
public void handlePitch(final PitchDetectionResult pitchDetectionResult, AudioEvent audioEvent) {
final float p = pitchDetectionResult.getPitch();
float cent = (float) (1200 * Math.log(p / 8.176) / Math.log(2)) % 12;
System.out.println(cent);
surfacePitchDrawingHelper.postRedraw(cent);
}
};
PitchProcessor.PitchEstimationAlgorithm algo = PitchProcessor.PitchEstimationAlgorithm.YIN; //use YIN
AudioProcessor pitchEstimator = new PitchProcessor(algo, sr, bs, printPitch);
d.addAudioProcessor(pitchEstimator);
// d.run();//starts the dispatching process <-- this was another bug in the original code (see update)!
AudioProcessor p = new PitchProcessor(algo, sr, bs, printPitch);
d.addAudioProcessor(p);
new Thread(d, "Audio Dispatcher").start();
...
}
请注意SurfacePitchDrawingHelper
封装了大部分与绘图相关的逻辑,而且子类MySurfaceView
中没有必要(我认为无论如何这都是个坏主意)。
主要想法是,在创建新SurfacePitchDrawingHelper
时,HandlerThread
创建专用Surface
。 HandlerThread
+ Looper
+ Handler
提供了一个有用的基础结构,可以在一个单独的线程上运行(以有效的方式)无限循环,该线程等待传入的消息并逐个处理它们。因此,除SurfaceHolder.Callback2
之外,其有效的公共API包含单个postRedraw
方法,可用于请求绘图线程执行另一次重绘,这正是自定义PitchDetectionHandler
使用的方法。 &#34;询问&#34;是通过在队列中放置一条消息来完成的,这个消息由绘图线程处理(更具体地说是我们在该线程上的自定义Handler
)。我没有把真正的公共API减少到有效的&#34;一,因为它使代码更复杂,我太懒了。但当然两个&#34;实现&#34;可以转移到内部类。
您有一个重要的决定:绘制线程是否应按顺序生成每个入站消息(所有cent
值),或者仅在绘制时发生最新消息。如果PitchDetectionHandler
产生的事件比&#34;绘制线程更快,那么这可能变得尤为重要。可以更新Surface
。我相信,对于大多数情况,只处理PitchDetectionHandler
中的最后一个值是可以的,但我在代码中留下了两个版本用于说明。目前,_processOnlyLast
字段在代码中实现了这种区别。很可能你应该做出这个决定,然后摆脱这个几乎不变的字段和无关分支中的代码。
当然,不要忘记将您的实际绘图逻辑放在doRedraw
更新(为什么后退按钮无法正常工作)
TLDR版本
违规行是
d.run();//starts the dispatching process
只是评论出来!
更长版本
查看您的示例,我们可以看到d
为AudioDispatcher
implements Runnable
,因此run
方法是在新线程上调用的方法。您可能会注意到这很重要,因为在此方法中会执行一些IO并阻止它运行的线程。所以在你的情况下它阻止了主UI线程。你要做几行
new Thread(d, "Audio Dispatcher").start();
这似乎是使用AudioDispatcher
这可以从我在评论中询问的堆栈跟踪中轻松看出。