玩短的声音Android的正确方法?

我正在创build一个将在屏幕上显示多个图像的应用程序,这些图像将是button,当点击时会播放短暂的声音。 我研究了这一点,只能find目前我用来播放声音的方法,这听起来似乎没有反应。 我希望声音能够快速播放,并且能够响应很多快速响应。 我不确定这是甚至可能在Android。

我用来播放声音的代码是这样的:

Button sound1; MediaPlayer firstSound; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); firstSound = MediaPlayer.create(SoundActivity.this, R.raw.click); sound1 = (Button) findViewById(R.id.Sound1); beaver.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { firstSound.start(); } }); } 

我的滞后问题也可能是我使用媒体播放器对象的方式? 我确实觉得这应该是在我的手机上更顺畅,任何有关如何播放Android声音的build议表示赞赏。

谢谢。

自从发现Sound Pool以来,我已经编辑了我的代码来使用它,它完美的工作,新的代码如下所示:

 SoundPool soundPool; HashMap<Integer, Integer> soundPoolMap; int soundID = 1; Button sound1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); soundPoolMap = new HashMap<Integer, Integer>(); soundPoolMap.put(soundID, soundPool.load(this, R.raw.click, 1)); sound1 = (Button) findViewById(R.id.bBeaver); sound1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); float curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); float maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float leftVolume = curVolume/maxVolume; float rightVolume = curVolume/maxVolume; int priority = 1; int no_loop = 0; float normal_playback_rate = 1f; soundPool.play(soundID, leftVolume, rightVolume, priority, no_loop, normal_playback_rate); } }); } 

谢谢

您可以使用SoundPool 。 它符合你想要做的完美。

您只需要一种方法来存储对应于每个图像(或button)的音效ID。

也许延长button来存储相关的音效ID。 当触摸button时,使用一个普通的SoundPool播放与id相关的音效。

您可以在这里阅读更多关于SoundPool的信息 。

@Rikonator在Soundpool的正确轨道上。 它更适合于你以后的function。

如果你决定去mediaplayer,不过,不要忘记prepareAsync()方法,以防止挂断UI线程。 你可以在这里阅读更多关于播放媒体。

 MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound); try { if (mp.isPlaying()) { mp.stop(); mp.release(); mp = MediaPlayer.create(getApplicationContext(), R.raw.sound); } mp.start(); } catch (Exception e) { e.printStackTrace(); }