How do I get a button to play a sound from raw when click? I just created a button with id button1
, but whatever code I write, all is wrong.
imp
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
Button one;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.soho);
one = (Button)this.findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
}
});
}
}
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MediaPlayer mp1 = MediaPlayer.create(this, R.raw.b1);
mp1.start();
}
});
Try this i think it will work
Instead of resetting it as proposed by DeathRs:
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
we can just reset the MediaPlayer to it's begin using:
if (mp.isPlaying()) {
mp.seekTo(0)
}
there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.
Nice!
MediaActionSound
A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs
use like:
fun playBeepSound() {
val sound = MediaActionSound()
sound.play(MediaActionSound.START_VIDEO_RECORDING)
}
public class MainActivity extends AppCompatActivity {
public void clickMe (View view) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
mp.start();
}
create a button with a method could be called when the button pressed (onCreate),
then create a variable for (MediaPlayer) class with the path of your file
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
finally run start method in that class
mp.start();
the file will run when the button pressed, hope this was helpful!
raw
folder, if it doesn't exists,
create one.-
or special characters in it.On your activity, you need to have a object MediaPlayer
, inside the onCreate
method or the onclick
method, you have to initialize the MediaPlayer
, like MediaPlayer.create(this, R.raw.name_of_your_audio_file)
, then your audio file ir ready to be played with the call for start()
, in your case, since you want it to be placed in a button, you'll have to put it inside the onClick
method.
Example:
private Button myButton;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mp = MediaPlayer.create(this, R.raw.gunshot);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
}
}