How to Clear or Release Audio Resources in Android?
Last Updated :
27 Jul, 2022
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.
- In this case, a sample MP3 file is taken in the raw folder.
- To create the "raw" folder right click on the res > New > Android Resource Directory and select the resource type as the raw.
- And after creating the folder add some sample audio file to play.
- Refer to the following video if unable to get the above steps.
Step 3: Working with the activity_main.xml
- In the activity_main.xml file, there is a simple PLAY button is implemented to start playing the audio file when clicked.
- Invoke the following code.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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
- Initiate the MediaPlayer instance with the raw resource to play the audio file.
- Invoke the following code to handle the play button to start playing the audio file.
- Comments are added inside the code for better understanding.
Java
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();
}
});
}
}
Kotlin
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
- This is one of the scenarios where the Audio resources can be released.
- In this case, the resources are released, after completely playing the audio file.
- Invoke the following code to implement the on completion listener for the mediaPlayer instance and release the Audio resources.
Java
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();
}
}
}
Kotlin
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.
- If the application is of the type of news reading or podcast, Whenever the user presses the back button or home button, the application will be in the Stop state.
- So at this condition, the onStop method needs to be overridden and the allocated Audio resources should be released or cleared.
- Invoke the following code to the MainActivity.java file.
Java
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();
}
}
}
Kotlin
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:
Similar Reads
Resource Raw Folder in Android Studio The raw (res/raw) folder is one of the most important folders and it plays a very important role during the development of android projects in android studio. The raw folder in Android is used to keep mp3, mp4, sfb files, etc. The raw folder is created inside the res folder: main/res/raw. So we will
4 min read
How to Fetch Audio file From Storage in Android? Selecting an audio file from the phone's storage is required when the user is uploading or sending an audio file in your application. So this article primarily focuses on getting the audio files as a URI from your phone's storage. Step by Step Implementation Step 1: Create a New Project To create a
2 min read
How to Play Audio from URL in Android? Many apps require the feature to add the audio feature in their application and there so many audio files that we have to play inside our application. If we will store so many audio files inside our application, then it will increase the size of the app and this may reduce the user base due to the h
4 min read
How to Manage Audio Focus in Android? The audio focus in Android needs to be managed and it is one of the important to handle the audio interruptions. In Android, many applications play media simultaneously, and to increase the User Experience the Audio interruptions are handled. For example, if the application is playing Audio, suddenl
5 min read
How to Delete Shared Preferences Data in Android? In Android, Shared Preferences is a method of storing and fetching primitive data with the help of a key. This is file is stored inside the application in the form of an XML file. It is used to save data of types int, long, string, boolean, etc. In this article, we will show you how you could save a
3 min read