简体   繁体   中英

How to stop a MediaPlayer using a button

The code I have so far is:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void SoundPlayer(View view) {
        MediaPlayer soundMediaPlayer1 = MediaPlayer.create(this, R.raw.gun_sound);
        soundMediaPlayer1.start();
    }

    public void DogSound(View view) {
        MediaPlayer soundMediaPlayer2 = MediaPlayer.create(this, R.raw.cat_sound);
        soundMediaPlayer2.start();
    }

    public void NewSound(View view) {
        MediaPlayer soundMediaPlayer3 = MediaPlayer.create(this, R.raw.new_sound);
        soundMediaPlayer3.start();
    }

    public void LaughTrack(View view) {
        MediaPlayer soundMediaPlayer12 = MediaPlayer.create(this, R.raw.laugh_sound);
        soundMediaPlayer12.start();
    }

    public void HorseSound(View view) {
        MediaPlayer soundMediaPlayer4 = MediaPlayer.create(this, R.raw.horse_sound);
        soundMediaPlayer4.start();
    }

    public void HeySound(View view) {
        MediaPlayer soundMediaPlayer5 = MediaPlayer.create(this, R.raw.hey_sound);
        soundMediaPlayer5.start();
    }

    private void Stop() {
        startActivity(new Intent(this, MainActivity.class));
    }

    public void stop(View view) {
        Stop();
    }

}

The problem I face is that all the sounds overlaps and plays. I have a STOP button set up, but have no idea has to how to make it stops the media. Any feedback is helpful.

Thank you.

First of all, I would use only one Instance of the MediaPlayer. You can then use mediaPlayer.stop() to stop a sound and prepare the next one. See the state diagram on https://developer.android.com/reference/android/media/MediaPlayer.html

1) Make the object of MediaPlayer in onCreate method don't create in every new method. 2) Before playing the music in another method first use stop() function to stop current playing sound(like mediaPlayer.stop(); ) then play the sound by start().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM