这是我的活动:
public class MainActivity extends AppCompatActivity { private SoundPool soundPool; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setVolumeControlStream(AudioManager.STREAM_MUSIC); soundPool = new SoundPool(5,AudioManager.STREAM_MUSIC,0); final int sound1 = soundPool.load(this,R.raw.whack,1); final int sound2 = soundPool.load(this,R.raw.miss,1); Button b1 = (Button) findViewById(R.id.b1); Button b2 = (Button) findViewById(R.id.b2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playSound(sound1); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playSound(sound2); } }); } private void playSound(int soundId) { AudioManager audioManager = (AudioManager) getSystemService(Context.AUdio_SERVICE); float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); soundPool.play(soundId,volume,1,1); } }
问题是当我点击Button1时,播放了sound1.然后当我一次又一次地点击Button1时,在我点击Button2之前什么也没有播放.当我这样做时,播放声音2.然后,如果我点击Button1,则播放sound1.当我一遍又一遍地点击Button2时会发生同样的情况.那么这里的问题是什么?
解决方法
根据
SoundPool.play()文档,卷值必须从0.0到1.0.但audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)返回更大的值(例如12).
因此,您应该设置正确的音量值.下面的工作代码:
因此,您应该设置正确的音量值.下面的工作代码:
public static void playAudio(Context context,SoundPool player,int soundId,float speed){ AudioManager mgr = (AudioManager) context.getSystemService(Context.AUdio_SERVICE); float actualVolume=(float) mgr.getStreamVolume(AudioManager.STREAM_MUSIC); float maxVolume=(float) mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume= actualVolume/maxVolume; player.play(soundId,speed); }