Play sound on button click android
Asked Answered
F

13

148

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.

import android.media.MediaPlayer;

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);
    MediaPlayer = mp;
    mp = MediaPlayer.create(this, R.raw.soho);
    zero.setOnCliclListener(new View.OnClickListener() )

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.basic_screen, menu);
        return true;
    }



}
Farseeing answered 27/8, 2013 at 7:8 Comment(2)
You'd probably want to have the resources managed automatically, so that you can call MusicManager.getInstance().play(this, R.raw.my_sound);. If so, this library might be for you: github.com/delight-im/Android-AudioTandie
I'm sorry but your code does not make sense: (1) Where is the code in the middle, it looks like outside any method which is not valid Java, (2) You didn't set any click event on button one, (3) Not sure what zero refers to as you didn't include the definition in your code, (4) Assuming zero is relevant somehow, you've assigned an empty click listener to it, meaning it will do nothing when clickedAirs
P
273

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();
            }
        });
    }
}
Pippo answered 27/8, 2013 at 7:21 Comment(2)
And by the Way its one.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { mp.start(); } }); Dont miss that!Tella
dont't for get to RELEASEBedplate
W
49

The best way to do this is here i found after searching for one issue after other in the LogCat

MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        mp.reset();
        mp.release();
        mp=null;
    }
});
mp.start();

Not releasing the Media player gives you this error in LogCat:

Android: MediaPlayer finalized without being released

Not resetting the Media player gives you this error in LogCat:

Android: mediaplayer went away with unhandled events

So play safe and simple code to use media player.

To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like

mp = MediaPlayer.create(context, R.raw.sound_two);

and play it !

Have fun!

Werewolf answered 4/7, 2014 at 8:26 Comment(0)
F
49

Tested and working 100%

public class MainActivity extends ActionBarActivity {
    Context context = this;
    MediaPlayer mp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        mp = MediaPlayer.create(context, R.raw.sound);
        final Button b = (Button) findViewById(R.id.Button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    if (mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                        mp = MediaPlayer.create(context, R.raw.sound);
                    } mp.start();
                } catch(Exception e) { e.printStackTrace(); }
            }
        });
    }
}

This was all we had to do

if (mp.isPlaying()) {
    mp.stop();
    mp.release();
    mp = MediaPlayer.create(context, R.raw.sound);
}
Feuchtwanger answered 25/8, 2015 at 14:38 Comment(1)
This works when replaying the audio as well. When playing sound I think mp.start() will work without the try / catch and if blocks.Glisson
S
10
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();
            }
        });
    }
}
Superfecundation answered 27/8, 2013 at 7:18 Comment(2)
Here is the result, again nothing works dropbox.com/s/9xb0lzesp0ibx9z/2.jpgFarseeing
You do not need the line mp=new MediaPlayer() because you are initializing it again using MediaPlayer.create(...) on the next line.Pippo
M
8
  • The audio must be placed in the raw folder, if it doesn't exists, create one.
  • The raw folder must be inside the res folder
  • The name mustn't have any - 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();
            }
        });
}
}
Mediator answered 10/8, 2018 at 19:12 Comment(0)
H
6

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)
}
Heeheebiejeebies answered 12/2, 2019 at 18:9 Comment(2)
please provide Java version; Your code is in KotlinEichman
@PeymanMajidi Java Version 'private void playBeepSound(){ MediaActionSound sound = new MediaActionSound(); sound.play(MediaActionSound.START_VIDEO_RECORDING); }'Inexistent
H
3
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

Houseless answered 10/12, 2017 at 18:58 Comment(0)
M
3

An edge case: Above every answer is almost correct but I was stuck in an edge case. If any user randomly clicks the button multiple times within a few seconds then after playing some sound it doesn't respond anymore.

Reason: Initialize Mediaplayer object is very expensive. It also deals with resources (audio file) so it takes some time for it. When users randomly initialize and calling a method of MediaPlayer's methods like start(), stop(), release(), etc can cause IllegalStateException which I faced.

Solution: Thanks caw for his suggestion in the comment about Android-Audio. It has just a simple two java classes (MusicManager.java, SoundManager.java).

You can use MusicManager.java if you want to play one-off sound files -

MusicManager.getInstance().play(MyActivity.this, R.raw.my_sound);

You can use SoundManager.java if you want to play multiple sounds frequently and fast -

class MyActivity extends Activity {

    private SoundManager mSoundManager;

    @Override
    protected void onResume() {
        super.onResume();

        int maxSimultaneousStreams = 3;
        mSoundManager = new SoundManager(this, maxSimultaneousStreams);
        mSoundManager.start();
        mSoundManager.load(R.raw.my_sound_1);
        mSoundManager.load(R.raw.my_sound_2);
        mSoundManager.load(R.raw.my_sound_3);
    }

    private void playSomeSound() {
        if (mSoundManager != null) {
            mSoundManager.play(R.raw.my_sound_2);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mSoundManager != null) {
            mSoundManager.cancel();
            mSoundManager = null;
        }
    }

}
Mercenary answered 17/8, 2020 at 5:25 Comment(0)
I
3

In Java:

private void playBeepSound(){
    MediaActionSound sound = new MediaActionSound();
    sound.play(MediaActionSound.START_VIDEO_RECORDING);
}
Inexistent answered 15/6, 2022 at 12:27 Comment(0)
P
2
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!

Prevalent answered 16/5, 2018 at 15:24 Comment(1)
Welcome to Stack Overflow! It would be better if you add some explanation and commenting to your code so future readers can learn from you.Olibanum
B
2

All these solutions "sound" nice and reasonable but there is one big downside. What happens if your customer downloads your application and repeatedly presses your button?

Your MediaPlayer will sometimes fail to play your sound if you click the button to many times.

I ran into this performance problem with the MediaPlayer class a few days ago.

Is the MediaPlayer class save to use? Not always. If you have short sounds it is better to use the SoundPool class.

A save and efficient solution is the SoundPool class which offers great features and increases the performance of you application.

SoundPool is not as easy to use as the MediaPlayer class but has some great benefits when it comes to performance and reliability.

Follow this link and learn how to use the SoundPool class in you application:

https://developer.android.com/reference/android/media/SoundPool

Youtube: Save Solution

Blockish answered 25/6, 2019 at 15:40 Comment(0)
A
2

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)
}
Angstrom answered 24/7, 2019 at 13:58 Comment(0)
C
1

check if mp != null then use the current function:

MediaPlayer mpClick;
private void onClickSound() {
    if(mpClick == null){
        mpClick = MediaPlayer.create(context,R.raw.tap);
    }
    if(mpClick.isPlaying())
    {
    }
    else
    {
        mpClick.start();
    }
}

usage:

Button button1=(Button)findViewById(R.id.btnB1);

button1.setOnClickListener(new OnClickListener(){
    public void onClick(View v) {
          onClickSound();
     }
});
Condonation answered 16/1, 2023 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.