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:)
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();
}
});
}
}
Click an image button match with sound effect
You might want to consider using a SoundPool
.
Try this:
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
HashMap<Integer, Integer> soundPoolMap soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(soundID, soundPool.load(this, R.raw.your_sound, 1));
And then play your sound using
soundPool.play(soundId, 1, 1, 1, 0, 0);
This answer is linked to this post:POST
How can I make a sound overlap when pressing a button multiple times?
I think creating a new MediaPlayer
each time you are clicking the button should work fine. I have not tested the code yet. Let me know if you get an error.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button that is pressed to play the sound.
imgBtn = findViewById(R.id.imageViewItm);
//Listener that will run the onClick() method when imgBtn is pressed.
imgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Plays sound
MediaPlayer sound = MediaPlayer.create(MainActivity.this, R.raw.sound_stuff);
sound.start();
}
});
}
Related Topics
Http Failure Response for (Unknown Url): 0 Unknown Error on Android
Imageview of Png Doesn't Appear (Maybe It's Too Big)
Suppress Keyboard from Popping Up
How to Check If the Current Activity Has a Dialog in Front
How to Remove Focus from Edittext When User Is Done Editing
Java.Io.Filenotfoundexception Open Failed Eacces (Permission Denied) on Device
How to Get the Current Time on a Button Click
How to Open Whatsapp Using an Intent in Your Android App
Html File Input Control With Capture and Accept Attributes Works Wrong
Best Practice For Instantiating a New Android Fragment
Android Emulator Is Start But Window Show Blank Screen
How to Set Spinner Default by Its Value Instead of Position
Open Play Store App from Browser Link
How to Center the Elements in Constraintlayout
Android No on Screen Keybord ( Only Voice )
React-Native: Images Not Showing in Android Device; But Shows in Emulator