dev_android
dev_android

Reputation: 493

Playing sound after click on imageview/button

I am trying to play click sound on image (ImageView/Button) click and I saw an example here. I have also tried to use this:

profile_pick.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
            Intent i=new Intent(getApplicationContext(),Profile_pic.class);
            startActivity(i);
            overridePendingTransition(R.anim.animation,R.anim.animation2);
        }
    });

but it's not working. Can anyone suggest how to do this?

(Adding a raw sound is not a good idea so I would prefer to use a use system sound... )

Upvotes: 0

Views: 7326

Answers (3)

Farouk Touzi
Farouk Touzi

Reputation: 3456

First, you need to put your statements inside a block, and in this case the onCreate method.

After that, you initialize the button as variable one, then you use a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.

Finally, put the logic to play the sound inside the onClick.

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BasicScreenActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_screen);

        Button one = (Button)this.findViewById(R.id.button1);
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
        one.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                mp.start();
            }
        });     
    }
}

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157447

add android:soundEffectsEnabled="true" to the profile_pick . The documentation says that

The sound effect will only be played if sound effects are enabled by the user, and isSoundEffectsEnabled() is true.

so both the conditions are mandatory. Here you can find the documentation

Upvotes: 3

Andrey Gagan
Andrey Gagan

Reputation: 1398

profile_pick.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        AudioManager audioManager = 
        (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        audioManager.playSoundEffect(SoundEffectConstants.CLICK); 
        Intent i=new Intent(getApplicationContext(),Profile_pic.class);
        startActivity(i);
        overridePendingTransition(R.anim.animation,R.anim.animation2);
    }
});

Upvotes: 1

Related Questions