Play sound on button click android
This is the most important part in the code provided in the original post.
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();
}
});
To explain it step by step:
Button one = (Button) this.findViewById(R.id.button1);
First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById
, passing the Id we assigned to it (in this example's case: R.id.button1
), to get the button that we need. We cast it as a Button
so that it is easy to assign it to the variable one
that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
This is how to initialize a MediaPlayer
. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create()
method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho
. We declare it as final
. Jon Skeet provided a great explanation on why we do so here.
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//code
}
});
Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener
of our button one
. Inside is only one method, onClick()
which contains what instructions the button should do on click.
public void onClick(View v) {
mp.start();
}
To play the sound, we call MediaPlayer's start()
method. This method starts the playback of the sound.
There, you can now play a sound on button click in Android!
Bonus part:
As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release()
method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener
to our mp
like so:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//code
}
});
Inside the onCompletion
method, we release it like so:
public void onCompletion(MediaPlayer mp) {
mp.release();
}
There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment
or Activity
that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.
Original Post
First. You should put your statements inside a block, and in this case the onCreate method.
Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.
Third, put the logic to play the sound inside the onClick.
In summary:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
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();
}
});
}
}
How do I play sound on button click in android studio?
Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);
Button play_button = (Button)this.findViewById(R.id.button);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Place your sound in res/raw folder.
android - how to make a button click play a sound file every time it been pressed?
You should put mp3 file in /assets folder.
put this code inside
onCreate()
method aftersetContentView()
final MediaPlayer mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("AudioFile.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});3.sound will be played again each time you press button. You don't have to write any extra code for that.
Note that AudioFile.mp3 is the name of the mp3 file in /assets folder
Hope this answer is helpful:)
Android: Playing an audio clip onClick
This won't create a bring up the MediaPlayer interface... it will just play the sound you want.
Button boton = (Button) findViewById(R.id.boton);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(TestSonido.this, R.raw.slayer);
mp.start();
}
});
In this case, R.raw.slayer
represents an audio file called slayer.mp3
that is stored in the res/raw/
folder and once you click the button the droid will rock you...
Play Sound on Button Click in Android giving Null Pointer Exception
The error is occurring because the sound .wav is not supported by the device that I am running on the test app. It is running on a different device that supports .wav file format. I have converted the file type to mp3 and now it is working on both devices.
Thanks to everyone for your reply...
Related Topics
How to Create Android Spinner Without Down Triangle on the Right Side of the Widget
How to Determine If an Android Service Is Running in the Foreground
Popupwindow $Badtokenexception: Unable to Add Window -- Token Null Is Not Valid
Android Toggle Button Custom Look
Android Resources$Notfoundexception: Resource Id #0X7F030027
Importing Module in Android Studio
Get Application Context Returns Null
Android: How to Center Title in Toolbar
Autocompletetextview with Custom Adapter and Filter
Drawing Multiple Lines in Edittext E.G. Notepad
Horizontal Scrolling Grid View
Android Cancel Toast When Exiting the App and When Toast Is Being Shown
Datepicker Shows Wrong Value of Month
How to Change Action Bar Title Color in Code
How to Handle Multiple Countdown Timers in Listview
Rotating a Bitmap Using Jni & Ndk
What's Better? Notifydatasetchanged or Notifyitemchanged in Loop
How to Create an Android Application in Android Studio That Uses the Google Maps API V2