Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

add sound to button onclick

Hello all how to add a sound to button (on click) in Android Studio, i searched but i all i found is for (Eclipse).

Thanks

2 Answers

here is a stack overflow answer

basically you need to create a folder called raw in your /res directory of your project and drag your sound file there. then use

in your on click method add

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
    mp.start();

Thanks a lot , it's work

cool. its probably better to add a memberVariable for your player and then just start it in the onClick listener

so add a member variable at the start of your class

private MediaPlayer mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);

and then inside the listener just start it

mMediaPlayer.start();