添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
体贴的黄瓜  ·  Optivara System AI ...·  1 月前    · 
爱喝酒的哑铃  ·  [Release] ...·  1 月前    · 
耍酷的移动电源  ·  CentOS ...·  2 年前    · 
胡子拉碴的饼干  ·  What do I replace ...·  2 年前    · 
冷静的签字笔  ·  VS ...·  2 年前    · 

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 diagram
  • Creating 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 Class

  • The playing of the audio or video file using MediaPlayer is done using a state machine.
  • The following image is the MediaPlayer state diagram.
State Diagram of the MediaPlayer class
  • 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.
State Diagram of the MediaPlayer class
  • 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.
State Diagram of the MediaPlayer class

Steps to create a simple MediaPlayer in Android

Step 1: Create an empty activity project

Step 2: Create a raw resource folder

  • Create a raw resource folder under the res folder and copy one of the .mp3 file extension.

Step 3: Working with the activity_main.xml file

  • The 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 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: 

Mediaplayer Class in Android

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

Similar Reads

Eye Detecting Video Player in Android
In this article, we are going to learn that how we can make an eye detecting video player and use third-party libraries in our android application. If you are a beginner in android development then by making this application you will boost your confidence and learn some interesting and new.What we a
4 min read
Multimedia Framework in Android
Android multimedia framework is designed to provide a reliable interface for java service. It is a system that includes multimedia applications, frameworks, an OpenCore engine, hardware devices for audio/video/ input, output devices also several core dynamic libraries such as libmedia, libmediaplays
5 min read
VideoView in Android
VideoView is a UI widget that is used to display video content to the users within android applications. We can add video in this video view from different resources such as a video stored on the user device, or a video from a server. In this article, we will take a look at How to use Video View in
3 min read
OOPs Concepts in Android
Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and code that manipulates that data. In Android, Java is the primary programming language used for developing Android apps. Java is an object-oriented language and it provide
8 min read
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It !