Android Media Player Song Featuring SeekBar

In this guide, we will utilize the MediaPlayer class to create a simple Audio Player within our Android Application. We will incorporate a Play/Stop functionality and provide the user with the ability to adjust the position of the song using a SeekBar.

One possible paraphrase for “Android MediaPlayer” is “Media player for Android devices.”

The MediaPlayer class is utilized for playing both Audio and Video files. We will primarily make use of the typical methods available in the MediaPlayer class.

  • start()
  • stop()
  • release() – To prevent memory leaks.
  • seekTo(position) – This will be used with the SeekBar
  • isPlaying() – Let’s us know whether the song is being played or not.
  • getDuration() – Is used to get the total duration. Using this we’ll know the upper limit of our SeekBar. This function returns the duration in milli seconds
  • setDataSource(FileDescriptor fd) – This is used to set the file to be played.
  • setVolume(float leftVolume, float rightVolume) – This is used to set the volume level. The value is a float between 0 an 1.

We will play an mp3 file retrieved from the Assets folder in our Android Studio Project.

AssetFileDescriptor descriptor = getAssets().openFd("filename");
                mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
                descriptor.close();

To develop an Application capable of playing audio and allowing users to modify the position of the current song track, we must incorporate three components.

  • MediaPlayer
  • SeekBar With Text – To show the current progress time besides the thumb.
  • Runnable Thread – To update the Seekbar.

Structure of the project.

Include the subsequent dependency in your build.gradle file.

implementation 'com.android.support:design:28.0.0-alpha3'

Write the following natively in a different way:

Piece of programming.

Below is the code for the activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="PLAY/STOP SONG.\nSCRUB WITH SEEKBAR"
        android:textStyle="bold" />


    <SeekBar
        android:id="@+id/seekbar"
        android:layout_margin="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:src="@android:drawable/ic_media_play"
        android:text="PLAY SOUND" />

</LinearLayout>

Below is the code for the MainActivity.java class, where we have included a FloatingActionButon that can be activated or deactivated by clicking on it.

package com.scdev.androidmediaplayersong;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements Runnable {


    MediaPlayer mediaPlayer = new MediaPlayer();
    SeekBar seekBar;
    boolean wasPlaying = false;
    FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        fab = findViewById(R.id.button);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSong();
            }
        });

        final TextView seekBarHint = findViewById(R.id.textView);

        seekBar = findViewById(R.id.seekbar);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                seekBarHint.setVisibility(View.VISIBLE);
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
                seekBarHint.setVisibility(View.VISIBLE);
                int x = (int) Math.ceil(progress / 1000f);

                if (x  0 && mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    clearMediaPlayer();
                    fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_play));
                    MainActivity.this.seekBar.setProgress(0);
                }

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {


                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(seekBar.getProgress());
                }
            }
        });
    }

    public void playSong() {

        try {


            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                clearMediaPlayer();
                seekBar.setProgress(0);
                wasPlaying = true;
                fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_play));
            }


            if (!wasPlaying) {

                if (mediaPlayer == null) {
                    mediaPlayer = new MediaPlayer();
                }

                fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_pause));

                AssetFileDescriptor descriptor = getAssets().openFd("suits.mp3");
                mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
                descriptor.close();

                mediaPlayer.prepare();
                mediaPlayer.setVolume(0.5f, 0.5f);
                mediaPlayer.setLooping(false);
                seekBar.setMax(mediaPlayer.getDuration());

                mediaPlayer.start();
                new Thread(this).start();

            }

            wasPlaying = false;
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public void run() {

        int currentPosition = mediaPlayer.getCurrentPosition();
        int total = mediaPlayer.getDuration();


        while (mediaPlayer != null && mediaPlayer.isPlaying() && currentPosition < total) {
            try {
                Thread.sleep(1000);
                currentPosition = mediaPlayer.getCurrentPosition();
            } catch (InterruptedException e) {
                return;
            } catch (Exception e) {
                return;
            }

            seekBar.setProgress(currentPosition);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearMediaPlayer();
    }

    private void clearMediaPlayer() {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }
}

When the FloatingActionButton is clicked in the code above, the playSong function is activated. In this function, the song is stopped, the MediaPlayer and FloatingActionButton icon are reset every second time. Once mediaPlayer.prepare() is called, the song details become available. The duration is obtained and set as the maximum position of the SeekBar. By setting looping to false, the song will not play infinitely until the user stops it. The thread is started, triggering the run method from the implemented Runnable interface. Inside the run method, the progress is updated every second, which triggers the onProgressChanged method of the SeekBar listener. In the listener, the TextView offset is set below the SeekBar’s thumb. The time duration is set by converting milliseconds to seconds. When the SeekBar is moved, the same method is triggered. When the user stops scrubbing the SeekBar, the onStopTrackingTouch method is triggered, and the song position is updated using the seekTo method on the MediaPlayer instance. Once the song is completed, the SeekBar position is reset to the initial position, and the MediaPlayer instance is cleared. The application output without audio is provided below. This concludes the tutorial. You can download the project from the link below and play the song yourself.

One option for paraphrasing “AndroidMediaPlayerSong” natively could be “Song played using the Android Media Player.”

Link to the project on GitHub

 

more  tutorials

Interview Questions and Answers specifically about Android(Opens in a new browser tab)

Toggle button in Android(Opens in a new browser tab)

get pandas DataFrame from an API endpoint that lacks order?(Opens in a new browser tab)

OkHttp on Android(Opens in a new browser tab)

BroadcastReceiver Example Tutorial on Android(Opens in a new browser tab)

 

Leave a Reply 0

Your email address will not be published. Required fields are marked *