我无法使用我的钢琴应用程序的SoundPool和Thread播放并行声音。
我想创建一个简单的1八度音阶钢琴,将mp3文件加载到原始文件夹中,问题是当我按下钢琴按钮时,如果尚未完成操作,新按下的键将剪切上一个声音。 然后我将“最后一个键”放入线程中,但仍然是同样的问题。
// my simple piano class
public class PianoDraw extends View {
public boolean onTouchEvent(MotionEvent event) {
final int x = (int) event.getX();
final int y = (int) event.getY();
i = -1;
for (Rect item : whiteArray) {
i += 1;
if (item.contains(x, y)) {
switch (i) {
// first key "Do" with no thread to play sound
case 0: {
soundPool.load(getContext(), R.raw.wk1, 1);
return super.onTouchEvent(event);
}
// I removed 5 other keys to short the code
// the last key with Thread
case 6: {
Thread myTheared = new Thread(new Runnable() {
@Override
public void run() {
soundPool.load(getContext(), R.raw.wk7, 1);
}
});
myTheared.start();
}
}//switch
}//if
}//for
return super.onTouchEvent(event);
}
声池初始化一次,加载后将播放声音,但不会并行播放
public void initSoundPool() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
soundPool = new SoundPool.Builder()
.setAudioAttributes(attributes)
.build();
} else {
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
}
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
soundPool.play(sampleId, 1.0f, 1.0f, 0, 0, 1.0f);
}
});
}
}
我应该使用soundTrack还是其他类?