Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android plays sounds after delay

Tags:

android

audio

I have to play sounds on GUI events, like clicking buttons etc. For this purpose, I call the following native code from WebView:

MediaPlayer _SoundPlayer = new MediaPlayer();
private void playSound(String sound)
{
    _SoundPlayer.reset();
    try
    {
        AssetFileDescriptor afd = getAssets().openFd("sound/" + sound + ".mp3");
        _SoundPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        _SoundPlayer.prepare();
        _SoundPlayer.start();
    }
    catch (Exception e) { }
}

The problem is there is a delay ~500ms between an event and its sound. Can I optimize playing sound somehow, maybe, creating a dedicated MediaPlayer instances for every kind of sound?

Regards,

like image 775
noober Avatar asked Dec 27 '22 22:12

noober


2 Answers

Use SoundPool for low-latency media playback, instead of MediaPlayer.

like image 88
Rajesh Avatar answered Jan 12 '23 07:01

Rajesh


I see that this already has an accepted answer, but I would add that there is no complete solution at this time: Android currently has very large audio latency. Devs are still waiting for a good solution.

This issue refers to the NDK, but the issue is general:

http://code.google.com/p/android/issues/detail?id=3434

like image 30
Tom Avatar answered Jan 12 '23 07:01

Tom