Media Player

Media Player in Android | Tutorial

The Media Player class can be used to control the playback of audio/video files and streams.

Playback of audio/video files and streams on Android can be controlled in a variety of ways. One of these methods is to use the MediaPlayer class.

A software or hardware device that can play media files or disks. For example, many modern media players are capable of playing audio files, for example. MP3 song files and video files, for example. B. The short video clip or movie to be played.

Preview: Media Player

<–Media Player Example

File:MainActivity.kt

package com.example.musicplayer

import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.Window
import android.view.WindowManager
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    private var handler: Handler = Handler()
    private lateinit var mediaPlayer: MediaPlayer
    private lateinit var runnable: Runnable
    private var Pause: Boolean = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.activity_main)
        //Play Button
        findViewById<Button>(R.id.Startbutton).setOnClickListener {
            if (Pause) {
                mediaPlayer.seekTo(mediaPlayer.currentPosition)
                mediaPlayer.start()
                Pause = false
                Toast.makeText(this, "Music playing", Toast.LENGTH_SHORT).show()
            } else {
                mediaPlayer = MediaPlayer.create(this, R.raw.spk)
                mediaPlayer.start()
                Toast.makeText(this, "Music playing", Toast.LENGTH_SHORT).show()
            }

            SeekBar()
            findViewById<Button>(R.id.Startbutton).isEnabled = false
            findViewById<Button>(R.id.PauseBtn).isEnabled = true
            findViewById<Button>(R.id.StopBtn).isEnabled = true


            mediaPlayer.setOnCompletionListener {
                findViewById<Button>(R.id.Startbutton).isEnabled = true
                findViewById<Button>(R.id.PauseBtn).isEnabled = false
                findViewById<Button>(R.id.StopBtn).isEnabled = false
                Toast.makeText(this, "End", Toast.LENGTH_SHORT).show()
            }

        }
        //Pause Button
        findViewById<Button>(R.id.PauseBtn).setOnClickListener {
            if (mediaPlayer.isPlaying) {
                mediaPlayer.pause()
                Pause = true
                findViewById<Button>(R.id.Startbutton).isEnabled = true
                findViewById<Button>(R.id.PauseBtn).isEnabled = false
                findViewById<Button>(R.id.StopBtn).isEnabled = true

            }
        }
        //Stop Button
        findViewById<Button>(R.id.StopBtn).setOnClickListener {
            if (mediaPlayer.isPlaying || Pause.equals(true)) {
                Pause = false
                findViewById<SeekBar>(R.id.seek_bar_id).setProgress(0)
                mediaPlayer.stop()
                mediaPlayer.reset()
                mediaPlayer.release()
                handler.removeCallbacks(runnable)
                findViewById<Button>(R.id.Startbutton).isEnabled = true
                findViewById<Button>(R.id.PauseBtn).isEnabled = false
                findViewById<Button>(R.id.StopBtn).isEnabled = false
                findViewById<TextView>(R.id.left_sec).text = ""
                findViewById<TextView>(R.id.right_sec).text = ""
                Toast.makeText(this, "Music stop", Toast.LENGTH_SHORT)

            }
        }

        //seek bar Setting
        findViewById<SeekBar>(R.id.seek_bar_id).setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, i: Int, b: Boolean) {
                if (b) {
                    mediaPlayer.seekTo(i * 1000)
                    
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                TODO("Not yet implemented")
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                TODO("Not yet implemented")
            }

        })


    }

    private fun SeekBar()
    {
        findViewById<SeekBar>(R.id.seek_bar_id).max = mediaPlayer.seconds
        runnable = Runnable {
            findViewById<SeekBar>(R.id.seek_bar_id).progress = mediaPlayer.currentSeconds
            findViewById<TextView>(R.id.left_sec).text = "${mediaPlayer.currentSeconds} sec"
            val diff = mediaPlayer.seconds - mediaPlayer.currentSeconds
            findViewById<TextView>(R.id.right_sec).text = "$diff sec"

            handler.postDelayed(runnable, 500)
        }
        handler.postDelayed(runnable, 500)
    }
}


val MediaPlayer.seconds: Int
    get() {
        return this.duration / 500
    }

val MediaPlayer.currentSeconds: Int
    get() {
        return this.currentPosition / 500
    }

File:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/PauseBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:enabled="false"
        android:text="Pause"
        android:textColor="@color/teal_200"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.791" />

    <Button
        android:id="@+id/Startbutton"
        android:layout_width="88dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="63dp"
        android:text="Play"
        android:textColor="@color/teal_200"
        app:layout_constraintBottom_toTopOf="@+id/PauseBtn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/StopBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:enabled="false"
        android:text="Stop"
        android:textColor="@color/teal_200"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.929" />

    <TextView
        android:id="@+id/left_sec"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:textColor="@color/black"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <TextView
        android:id="@+id/right_sec"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="52dp"
        android:layout_marginRight="52dp"
        android:textColor="@color/black"
        app:layout_constraintEnd_toEndOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <SeekBar
        android:id="@+id/seek_bar_id"
        style="@style/Widget.AppCompat.SeekBar.Discrete"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/left_sec"
        android:layout_marginBottom="48dp"
        android:saveEnabled="false"
        app:layout_constraintBottom_toTopOf="@+id/Startbutton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="410dp"
        android:layout_height="330dp"
        android:layout_marginBottom="19dp"
        android:scaleType="centerCrop"
        android:src="@drawable/music"
        app:layout_constraintBottom_toTopOf="@+id/seek_bar_id"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.2" />


</androidx.constraintlayout.widget.ConstraintLayout>
  •  Let us try to run your application. I’m assuming you’ve connected your Android smartphone to your PC. Open one of your project’s activity files and click the Run icon from the toolbar to run the app in android studio.
  • By default, you would see the pause and stop button disabled. Now press the play button and it would become disabled and the pause and stop button become enabled. It is shown in the above video.
  • Up till now, the music has been playing. Now press the pause button and the play and stop buttons are enabled and the pause button is disabled.
  • If we press the stop button then the music will stop and the play button is enabled, if we press the play button again then the music will start from an initial state.
  • While you are doing other things on your phone, your music will continue to play in the background. You must exit this application from background activities in order to stop it.

http://theudaipurstore.com

How to Create Calculator App with Example in Android

Creating a Flashlight Android Application

Complete Happy Birthday App in Android

Leave a Reply