How to Play Sound on Android Button Click
This tutorial explains step by step for how to add play sound effect on button click in Android Application.
Please follow the steps below in order to add sound on button click in Android Application:
1.First Add a button in Android Studio.
2.Go to MainActivity.java. text and give an id to the button
3.Now add the media player.
4.Go to res > New > Android resource directory
5.Now you can find raw under the res category.
6.Add a sample.mp3 file under raw.
7.Add the setOnclicklistener, so that when the button is pressed you will hear the sound.
8.Go to the live device view. On pressing the button, you will hear a long sound.
Complete Code
public class MainActivity extends AppCompatActivity{
Button bt;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button)findViewById(R.id.clickme);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sample);
bt.setOnClickListener(new View.OnClickListener(){
@Overridepublic void onClick(View view){
np.start();
}
}
}
}