2

I'm using MediaPlayer for play a click sound when user clicks on a button. Sometimes the sound will play fine but other times it is too slow. For example first click is fine but second click is too slow.
Here is my code:

private MediaPlayer mClickSound;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    mClickSound = MediaPlayer.create(this, R.raw.click);
}

@Override
public void onClick(View view) {
    try {
        if (mClickSound.isPlaying()) {
            mClickSound.stop();
            mClickSound.release();
            mClickSound = MediaPlayer.create(this, R.raw.click);
        }
        mClickSound.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
hosseinAmini
  • 2,184
  • 2
  • 20
  • 46

2 Answers2

0

Try this:

mClickSound.reset();
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.click);
if (afd == null) return;
mClickSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mClickSound.start();
afd.close();

setDataSource is taken from here: https://stackoverflow.com/a/20111291/6159609

The reset method is supposed to be faster.

Community
  • 1
  • 1
Kirk_hehe
  • 449
  • 7
  • 17
0

Please try below code working fine for me...

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    Button btn;
    MediaPlayer mClickSound;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
        mClickSound = MediaPlayer.create(this, R.raw.click);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (mClickSound.isPlaying()) {
            mClickSound.reset();
        }
        else {
            mClickSound = MediaPlayer.create(this, R.raw.click);
            mClickSound.start();
        }
    }
}
Patel Vicky
  • 766
  • 8
  • 17