Playing sound after click on imageview/button

时间秒杀一切 提交于 2019-12-04 21:17:02

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

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

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();
            }
        });     
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!