MediaPlayer Class in Android Last Updated : 12 Aug, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network. So in this article, the things discussed are:MediaPlayer State diagramCreating a simple audio player using MediaPlayer API. Have a look at the following image. Note that we are going to implement this project using the Kotlin language. State Diagram of the MediaPlayer ClassThe playing of the audio or video file using MediaPlayer is done using a state machine.The following image is the MediaPlayer state diagram.In the above MediaPlayer state diagram, the oval shape represents the state of the MediaPlayer instance resides in.There are two types of arcs showing in the state diagram. One with the single arrowhead represents the synchronous method calls of the MediaPlayer instance and one with the double arrowhead represents the asynchronous calls.The release method which is one of the important element in the MediaPlayer API. This helps in releasing the Memory resources allocated for the Mediaplayer instance when it is not needed anymore. Refer to How to Clear or Release Audio Resources in Android? to know how the memory allocated by the Mediaplayer can be released. So that the memory management is done accordingly.If the stop() method is called using Mediaplayer instance, then it needs to prepared for the next playback.The MediaPlayer can be moved to the specific time position using seekTo() method so that the MediaPlayer instance can continue playing the Audio or Video playback from that specified position.The focus of the audio playback should be managed accordingly using the AudioManager service which is discussed in the article How to Manage Audio Focus in Android?.The following image is the summarised version of the MediaPlayer state diagram.Steps to create a simple MediaPlayer in AndroidStep 1: Create an empty activity projectCreate an empty activity Android Studio project. And select Kotlin as a programming language.Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project.Step 2: Create a raw resource folderCreate a raw resource folder under the res folder and copy one of the .mp3 file extension.Step 3: Working with the activity_main.xml fileThe layout of the application consists of three buttons PLAY, PAUSE, and STOP mainly, which is used to control the state of the MediaPlayer instance.Invoke the following code inside the activity_main.xml file to implement the UI. 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"> <TextView android:id="@+id/headingText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:text="MEDIA PLAYER" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/headingText" android:layout_marginTop="16dp" android:gravity="center_horizontal"> <Button android:id="@+id/stopButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:backgroundTint="@color/colorPrimary" android:text="STOP" android:textColor="@android:color/white" /> <Button android:id="@+id/playButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:backgroundTint="@color/colorPrimary" android:text="PLAY" android:textColor="@android:color/white" /> <Button android:id="@+id/pauseButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimary" android:text="PAUSE" android:textColor="@android:color/white" /> </LinearLayout> </RelativeLayout> Output UI: Step 4: Working with the MainActivity.kt file The MediaPlayer instance needs the attributes needs to be set before playing any audio or video file.Invoke the following inside the MainActivity.kt file. Comments are added for better understanding. Kotlin import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create an instance of mediplayer for audio playback val mediaPlayer: MediaPlayer = MediaPlayer.create(applicationContext, R.raw.music) // register all the buttons using their appropriate IDs val bPlay: Button = findViewById(R.id.playButton) val bPause: Button = findViewById(R.id.pauseButton) val bStop: Button = findViewById(R.id.stopButton) // handle the start button to // start the audio playback bPlay.setOnClickListener { // start method is used to start // playing the audio file mediaPlayer.start() } // handle the pause button to put the // MediaPlayer instance at the Pause state bPause.setOnClickListener { // pause() method can be used to // pause the mediaplyer instance mediaPlayer.pause() } // handle the stop button to stop playing // and prepare the mediaplayer instance // for the next instance of play bStop.setOnClickListener { // stop() method is used to completely // stop playing the mediaplayer instance mediaPlayer.stop() // after stopping the mediaplayer instance // it is again need to be prepared // for the next instance of playback mediaPlayer.prepare() } } } Output: Run on Emulator Comment More infoAdvertise with us Next Article MediaPlayer Class in Android A adityamshidlyali Follow Improve Article Tags : Android Technical Scripter 2020 Android Projects Similar Reads Android Architecture Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern 5 min read Types of Functional dependencies in DBMS In relational database management, functional dependency is a concept that specifies the relationship between two sets of attributes where one attribute determines the value of another attribute. It is denoted as X â Y, where the attribute set on the left side of the arrow, X is called Determinant, 6 min read Understanding TF-IDF (Term Frequency-Inverse Document Frequency) TF-IDF (Term Frequency-Inverse Document Frequency) is a statistical measure used in natural language processing and information retrieval to evaluate the importance of a word in a document relative to a collection of documents (corpus). Unlike simple word frequency, TF-IDF balances common and rare w 6 min read List Comprehension in Python List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example, 4 min read Android Tutorial In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor 15+ min read Mean, Median and Mode Mean, Median, and Mode are measures of the central tendency. These values are used to define the various parameters of the given data set. The measure of central tendency (Mean, Median, and Mode) gives useful insights about the data studied, these are used to study any type of data such as the avera 15+ min read Stock Buy and Sell - Max one Transaction Allowed Given an array prices[] of length N, representing the prices of the stocks on different days, the task is to find the maximum profit possible by buying and selling the stocks on different days when at most one transaction is allowed. Here one transaction means 1 buy + 1 Sell.Note: Stock must be boug 8 min read 30 Days of SQL - From Basic to Advanced Level This basic to advanced SQL tutorial covers the entire SQL syllabus in a structured way and provides the best learning material and strategies to master complete SQL in 30 Days. We have laid out the complete SQL roadmap, and following this roadmap, you will learn all the concepts of SQL. All Importan 8 min read Data Scientist Roadmap - A Complete Guide [2025] Welcome to your comprehensive Data Science Roadmap! If youâve ever wondered, about âSteps or Path to Become a Data Scientistâ, youâre in the right place. This guide is perfect for Data Science for Beginners and seasoned professionals alike, covering everything from mastering Python for Data Science 8 min read What is An Event Loop in JavaScript? The event loop is an important concept in JavaScript that enables asynchronous programming by handling tasks efficiently. Since JavaScript is single-threaded, it uses the event loop to manage the execution of multiple tasks without blocking the main thread.JavaScriptconsole.log("Start"); setTimeout( 4 min read Like