Note that there are some explanatory texts on larger screens.

plurals
  1. POThe correct way to play short sounds Android?
    text
    copied!<p>I am creating an application that will have multiple images on the screen, these images will be buttons and when tapped will play a short sound. I researched this and could only find the current method I am using to play sounds, which does not seem responsive at all. I want that the sound plays quickly and is responsive to many rapid taps. I was unsure if this was even possible in Android.</p> <p>The code I am using to play my sound is this:</p> <pre><code> 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(); } }); } </code></pre> <p>My lag issue could also be perhaps down to the way I am using the media player object? I do feel that this should be smoother on my phone, any suggestions on how to play sounds in Android is appreciated.</p> <p>Thanks.</p> <p>Since discovering Sound Pool, I have edited my code to use this and it works perfectly, the new code looks like this:</p> <pre><code>SoundPool soundPool; HashMap&lt;Integer, Integer&gt; 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&lt;Integer, Integer&gt;(); 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); } }); } </code></pre> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload