diamondhands003
diamondhands003

Reputation: 497

Playing default android sound of button, clicking onTouch() method

In my android app I have some buttons, that should work with onTouch() method, course I need to change button's text, when finger in ACTION_DOWN position. But this buttons should to play default android sound of button clicking (like in onClick() method). Where I can find such sound? I think, it must be in SDK, but how can I find it? And what methods are better for such operation? I'm using MediaPlayer.

Listing:

public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        addTextShadow(v);
        Log.v(LOG_TAG, "ACTION_DOWN");
        break;
    case MotionEvent.ACTION_MOVE:
        clearTextShadow(v);
        isMoved = true;
        Log.v(LOG_TAG, "ACTION_MOVE");
        break;
    case MotionEvent.ACTION_UP:
        Log.v(LOG_TAG, "ACTION_UP");
        if (!isMoved) {
            clearTextShadow(v);
            if (v.getId() == R.id.btn_new) {
                Log.v(LOG_TAG, "New pressed");

                            playSound(); //MY METHOD TO PLAY SOUND

            } else if (v.getId() == R.id.btn_saved) {
                Log.v(LOG_TAG, "Saved pressed");
            } else if (v.getId() == R.id.btn_random) {
                Log.v(LOG_TAG, "Random pressed");
            }
        }
        isMoved = false;
        break;
    }
    return true;
}

And my playSound() method:

    public void playSound(){
    if (mp != null) {
        mp.release();
        mp = null;
    }
    try {
        mp = MediaPlayer
    .create(MyActivity.this, R.raw.sound); //BUT HERE I NEED DEFAULT SOUND!
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 27

Views: 21652

Answers (3)

bapho
bapho

Reputation: 936

Consider using view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);.

It will do both: playing the default sound and vibrate if the user has it enabled in the global settings.

Upvotes: 0

A Random Android Dev
A Random Android Dev

Reputation: 2691

Use this code in your onTouch() method:

view.playSoundEffect(android.view.SoundEffectConstants.CLICK);

If you are simply looking for a preset Android sound then it's better to use this functionality that's provided to you for free by the framework. Doing anything else, unless necessary for customization, would simply result in you working against the framework instead of working with it.

Upvotes: 79

dimetil
dimetil

Reputation: 3881

Use default sounds from /system/media/audio/

MediaPlayer or SoundPool will help to implement playback.

Upvotes: 0

Related Questions