我一直在为我的手机开发简单的鼓垫,但在同时播放两个声音时遇到了障碍(即在多点触控事件中,当用户同时按下两个或多个鼓声时) .
为了播放声音,我一直在使用 SoundPool 类。我有一个 HashMap,可以将一个 Point 散列为一个声音。所以我的想法是当一个点被按下时,它对应的声音就会播放。
我有一种感觉,让两个声音同时播放需要 fork 或创建新线程,但它并没有像我尝试的那样工作,它只是在“for each”循环中为每个点创建一个新线程按下。
提前致谢! -阿尼姆
编辑:
SoundPool database = new SoundPool(6,AudioManager.STREAM_MUSIC,100);
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec); //switched for convenience
height = MeasureSpec.getSize(heightMeasureSpec);
screenFactor = (int)((height*width)/6);
//have to add all points to the hash map
widthIncrement = (int)(width/3);
heightIncrement = (int)(height/2);
pointMap.put(new Point(0,0), database.load(getContext(),R.raw.clv,1));
pointMap.put(new Point(widthIncrement,0), database.load(getContext(),R.raw.pedalhh,1));
pointMap.put(new Point((widthIncrement*2),0), database.load(getContext(),R.raw.shake,1));
pointMap.put(new Point(0,heightIncrement), database.load(getContext(),R.raw.analoghat,1));
pointMap.put(new Point(widthIncrement,heightIncrement), database.load(getContext(),R.raw.kick,1));
pointMap.put(new Point((widthIncrement*2),heightIncrement), database.load(getContext(),R.raw.snare,1));
}
public boolean onTouchEvent(MotionEvent ev) {
if(ev.getAction()==ev.ACTION_DOWN){
AudioManager mgr = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
int streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
PointF[] touchPoints = new PointF[ev.getPointerCount()];
for(int i = 0; i < ev.getPointerCount(); i++){
if(ev.getPointerId(i)==ev.ACTION_DOWN){
touchPoints[i] = new PointF(ev.getX(i),ev.getY(i));
}
}
int i = 1;
for(final PointF point : touchPoints){
new Thread(new Runnable(){
public void run(){
forkSound(point);
}
}).start();
}
return true;
}
return true;
}
最佳答案
SoundPool 能够同时播放多个内容。您在设置 SoundPool 时传入流的数量。
发布所有用于创建和设置音池的代码,我们可以了解为什么它无法按您希望的方式工作。
第一个参数是 int maxStreams。无论您为此参数传递什么,都将是您的 soundpool 一次可以播放多少个流
关于android - Android 设备上的并发声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8734827/