我有一个 Soundpool,它会在 View 动画开始后播放一个简短的音效。问题是它只播放第一次的声音,而不是任何连续的时间。
我检查了 sound.play 函数的返回结果,它始终是 streamID,从不为零。它在需要时创建流,但声音只在第一次播放。声音只加载一次,所以它应该不是加载问题,因为它是第一次播放。我将粘贴下面的代码:
我正在调用 createSoundPool() 来构建声音池
private void createSoundPool() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
createNewSoundPool();
} else {
createOldSoundPool();
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void createNewSoundPool(){
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
sounds = new SoundPool.Builder().setMaxStreams(5)
.setAudioAttributes(attributes)
.build();
}
@SuppressWarnings("deprecation")
private void createOldSoundPool(){
sounds = new SoundPool(5, AudioManager.STREAM_MUSIC,0);
}
这就是我使用它的方式
public MyTouchListener(final Context context, final RecyclerView recyclerView,
OnTouchActionListener onTouchActionListener){
mOnTouchActionListener = onTouchActionListener;
initAnim();
createSoundPool();
drawCardSound = sounds.load(context,R.raw.drawcard,1); //this is where the soundID is created. Only once the class is instantiated
mGestureDetector = new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
return false;
}
// Find the item view that was swiped based on the coordinates
final View child = recyclerView.findChildViewUnder(e1.getX(), e1.getY());
final int childPosition = recyclerView.getChildAdapterPosition(child);
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if (mOnTouchActionListener != null && child != null) {
if(!animation.hasStarted() || animation.hasEnded()) {
child.startAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
int res=sounds.play(drawCardSound,3,3,1,0,1f);// sound is being played here
Log.e("test", "onAnimationStart: "+res );
}
LogCat 显示一个递增的流 ID,并且从不为零,所以我认为它应该正确触发。
更新: 这个问题只发生在 Lollipop 和上面我已经在 Lollipop 下面的模拟器上测试了它,声音工作正常。 Lollipop 及更高版本是否有一些错误?我在三星 S7 上测试过
最佳答案
发现问题了!所以显然 SoundPool.Play() 不能为左右音量取大于 1.0 的值。这适用于低于 Lollipop 的 API,但不适用于高于 Lollipop 的 API。我已将值降低到 1.0,现在它工作正常
关于android - Sound Pool 只播放一次声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51693085/