Playing sound after click on imageview/button

2019-04-17 10:25发布

问题:

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... )

回答1:

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



回答2:

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);
    }
});


回答3:

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();
            }
        });     
    }
}


标签: android click