Open In App

How to Clear or Release Audio Resources in Android?

As the memory consumption in Android is prioritized more, if the Application is using the Mediaplayer API, most of the memory resources are allocated. The developer needs to take care when the Mediaplayer instance is no longer needed or after completion of playing the media resource file. So in this article, it’s been discussed how the media player resources can be released in various scenarios step-by-step so that the memory consumption of the application is stable.

Steps to Release the Audio Resources

Step 1: Create an Empty Activity Android Studio project.



Step 2: Preparing the sample Audio file to play.

Step 3: Working with the activity_main.xml






<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
 
    <!--simple button to play the audio file-->
    <!--give appropriate id to handle it in the java file-->
    <Button
        android:id="@+id/play_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:backgroundTint="@color/colorPrimary"
        android:text="PLAY"
        android:textColor="@android:color/white"
        android:textSize="18sp" />
 
</RelativeLayout>

Output UI:

Step 4: Working with the MainActivity.java file




import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity {
 
    // Mediaplayer instance to initiate the audio file to play
    MediaPlayer mediaPlayer;
 
    // Button instance to handle the PLAY button
    Button bPlay;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
 
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
 
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });
    }
}




import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
class MainActivity : AppCompatActivity() {
    // Mediaplayer instance to initiate the audio file to play
    var mediaPlayer: MediaPlayer? = null
 
    // Button instance to handle the PLAY button
    var bPlay: Button? = null
 
    // Implement the on completion listener callback to do
    // the actions on the media player instance
    // when the audio file gets completely played
    var onCompletionListener = OnCompletionListener { releaseMediaPlayerResources() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button)
 
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song)
 
        // handle the play button
        bPlay.setOnClickListener(object : OnClickListener() {
            fun onClick(v: View?) {
                mediaPlayer!!.start()
                mediaPlayer!!.setOnCompletionListener(onCompletionListener)
            }
        })
    }
}
//This code is written by Ujjwal Kumar Bhardwaj

Output: Run on Emulator

Various scenarios where the Audio resources can be released or cleared

Note: In this case, there are two scenarios that have been shown for demonstration purpose. There can be more other scenarios where the audio resources can be released.

Scenario 1: After completely playing the audio file




import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity {
 
    // Mediaplayer instance to initiate
      // the audio file to play
    MediaPlayer mediaPlayer;
 
    // Button instance to handle the PLAY button
    Button bPlay;
 
    // Implement the on completion listener callback to do the
      // actions on the media player instance
    // when the audio file gets completely played
    MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayerResources();
        }
    };
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
 
        // prepare the audio file for
          // mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
 
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
 
                mediaPlayer.setOnCompletionListener(onCompletionListener);
            }
        });
    }
 
    // dedicated function is made to check the
      // mediaPlayer instance is null or not
    // based on that the actions are taken on
      // the mediaPlayer instance
    void releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
 
            // it is safe to stop playing the audio
              // file before releasing the audio file
            mediaPlayer.stop();
 
            // after stop playing the audio file
              // release the audio resources
            mediaPlayer.release();
        }
    }
}




import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
class MainActivity : AppCompatActivity() {
    // Mediaplayer instance to initiate the audio file to play
    var mediaPlayer: MediaPlayer? = null
 
    // Button instance to handle the PLAY button
    var bPlay: Button? = null
 
    // Implement the on completion listener callback to do
    // the actions on the media player instance
    // when the audio file gets completely played
    var onCompletionListener = OnCompletionListener { releaseMediaPlayerResources() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button)
 
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song)
 
        // handle the play button
        bPlay.setOnClickListener(object : OnClickListener() {
            fun onClick(v: View?) {
                mediaPlayer!!.start()
                mediaPlayer!!.setOnCompletionListener(onCompletionListener)
            }
        })
    }
 
    // dedicated function is made to check the
    // mediaPlayer instance is null or not
    // based on that the actions are taken
    // on the mediaPlayer instance
    fun releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
 
            // it is safe to stop playing the audio file
            // before releasing the audio file
            mediaPlayer!!.stop()
 
            // after stop playing the audio file
            // release the audio resources
            mediaPlayer!!.release()
        }
    }
}
//This code is written by Ujjwal Kumar Bhardwaj

Scenario 2: When the user presses the back or home button.




import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity {
 
    // Mediaplayer instance to initiate the audio file to play
    MediaPlayer mediaPlayer;
 
    // Button instance to handle the PLAY button
    Button bPlay;
 
    // Implement the on completion listener callback to do
      // the actions on the media player instance
    // when the audio file gets completely played
    MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayerResources();
        }
    };
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
 
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
 
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
 
                mediaPlayer.setOnCompletionListener(onCompletionListener);
            }
        });
    }
 
    @Override
    protected void onStop() {
 
        // Before going to stop state release the
          // allocated mediaplyer resources
        releaseMediaPlayerResources();
 
        super.onStop();
    }
 
    // dedicated function is made to check the
      // mediaPlayer instance is null or not
    // based on that the actions are taken
      // on the mediaPlayer instance
    void releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
 
            // it is safe to stop playing the audio file
              // before releasing the audio file
            mediaPlayer.stop();
 
            // after stop playing the audio file
              // release the audio resources
            mediaPlayer.release();
        }
    }
}




import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
class MainActivity : AppCompatActivity() {
    // Mediaplayer instance to initiate the audio file to play
    var mediaPlayer: MediaPlayer? = null
 
    // Button instance to handle the PLAY button
    var bPlay: Button? = null
 
    // Implement the on completion listener callback to do
    // the actions on the media player instance
    // when the audio file gets completely played
    var onCompletionListener = OnCompletionListener { releaseMediaPlayerResources() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button)
 
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song)
 
        // handle the play button
        bPlay.setOnClickListener(object : OnClickListener() {
            fun onClick(v: View?) {
                mediaPlayer!!.start()
                mediaPlayer!!.setOnCompletionListener(onCompletionListener)
            }
        })
    }
 
    override fun onStop() {
 
        // Before going to stop state release the
        // allocated mediaplyer resources
        releaseMediaPlayerResources()
        super.onStop()
    }
 
    // dedicated function is made to check the
    // mediaPlayer instance is null or not
    // based on that the actions are taken
    // on the mediaPlayer instance
    fun releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
 
            // it is safe to stop playing the audio file
            // before releasing the audio file
            mediaPlayer!!.stop()
 
            // after stop playing the audio file
            // release the audio resources
            mediaPlayer!!.release()
        }
    }
}
//This code is written by Ujjwal umar Bhardwaj

The audio should be stopped when the home button is pressed. Like the following:


Article Tags :