Search code examples
javaandroidandroid-mediaplayer

Button sound effect only works 28 times


I have set a gunshot sound to play every time I press a button (It is a fire button so it needs to be clicked many times). When I run the program, the gunshot sound plays every time I press it, but after the 28th time the button is pressed, the sound is no longer played. However, the Toast I added still works. Any idea why this is?

activity_main.xml:

 <Button
        android:id="@+id/fire"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fire"
        android:onClick="fire"
        android:textSize="35sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

Main.java:

package com.example.brans.zoombie;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class Main extends AppCompatActivity {

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

public void fire(View v){
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
    mp.start();
    Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
}
}

After the 29th Time, the logcat says this.

04-02 16:07:56.371 23703-23717/com.example.brans.zoombie       V/MediaPlayer:message received msg=100, ext1=1, ext2=-19
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie E/MediaPlayer: error (1, -19)
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: callback application
04-02 16:07:56.371 23703-23717/com.example.brans.zoombie V/MediaPlayer: back from callback

Solution

  • You should remove media player from RAM to avoid out of memory exceptions.

    public void fire(View v){
        MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.pistol);
        mp.start();
        Toast.makeText(this, "shot fired", Toast.LENGTH_SHORT).show();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mp.stop();
            if (mp != null) {
                mp.release();
            }
    
          }
        });
    }