Android MediaPlayer Example

Android MediaPlayer

Android MediaPlayer – You Know Very Well About Android Mediaplayer We Use Differents Of Android Music Player Apps On Our Smartphone Vlc,mxplayer, Android Default Music Player And Much More, But In This Tutorial We Teach That How To Develop Your Own Android Mediaplayer From Sratch So Let’s Start . Android facilitate many ways to regulate playback of audio/video files. Among this way is by using a class known as MediaPlayer.

android mediaplayer

Android offers MediaPlayer class to gain access to built-in mediaplayer services like participating in audio, video e.t.c. To be able to use MediaPlayer, we must call a static Method create() of the class. This technique returns an example of MediaPlayer. Its syntax is really as follows

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

 

The next parameter is the name of the songs that you would like to play. You must make a fresh folder under assembling your project with name raw and place the music record into it.

When  you’ve created the Mediaplayer object  you can call some methods to get started on or stop the music. These procedures are the following.

mediaPlayer.start();
mediaPlayer.pause();

 

On call to start out() method, the music begins playing right from the start. If this technique is named again following the pause() method, the music would start participating in from where it is kept and not right from the start. In order to start out music right from the start, you have to call reset() method. When listener wants to play music from 0 means from beginning. Its code is given below

mediaPlayer.reset();

so this is not necessary but In addition to the start and pause method, there are other methods provided by this class for better working with audio/training video files. These procedures are the following

Android MediaPlayer Methods

  1. isPlaying()
  2. seekTo(position)
  3. getCurrentDuration()
  4. getDuration()
  5. reset()
  6. release()
  7. setVolume(float leftVolume, float rightVolume)
  8. setDataSource(FileDescriptor fd)
  9. selectTrack(int index)
  10. getTrackInfo()

Android MediaPlayer Example

Here is a good android mediaplayer example demonstrating the utilization of MediaPlayer. It creates a simple media player which allows you to forwards, backward, play and pause a melody. To test out this android mediaplayer example, you will need to perform this on a genuine device to listen to the sound audio.

Steps     Description

  1. You use Android studio room IDE to produce an Android program under a package deal com.example.androdevelopment.myapplication.
  2. Modify src/MainActivity.java document to include MediaPlayer code.
  3. Modify the res/layout/activity_main to include respected XML components
  4. Create a fresh folder under MediaPlayer with name as raw and place an mp3 music record in it with name as track.mp3
  5. Run the application form and choose a jogging android os device and set up the application onto it and validate the results

Modified Content Of Main Activity – > src/MainActivity.java.

package com.example.androdevelopment.myapplication;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;


public class MainActivity extends Activity {
   private Button b1,b2,b3,b4;
   private ImageView iv;
   private MediaPlayer mediaPlayer;
  
   private double startTime = 0;
   private double finalTime = 0;
  
   private Handler myHandler = new Handler();;
   private int forwardTime = 5000;
   private int backwardTime = 5000;
   private SeekBar seekbar;
   private TextView tx1,tx2,tx3;

   public static int oneTimeOnly = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      b1 = (Button) findViewById(R.id.button);
      b2 = (Button) findViewById(R.id.button2);
      b3 = (Button)findViewById(R.id.button3);
      b4 = (Button)findViewById(R.id.button4);
      iv = (ImageView)findViewById(R.id.imageView);

      tx1 = (TextView)findViewById(R.id.textView2);
      tx2 = (TextView)findViewById(R.id.textView3);
      tx3 = (TextView)findViewById(R.id.textView4);
      tx3.setText("Song.mp3");

      mediaPlayer = MediaPlayer.create(this, R.raw.song);
      seekbar = (SeekBar)findViewById(R.id.seekBar);
      seekbar.setClickable(false);
      b2.setEnabled(false);

      b3.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Playing 
               sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.start();

            finalTime = mediaPlayer.getDuration();
            startTime = mediaPlayer.getCurrentPosition();

            if (oneTimeOnly == 0) {
               seekbar.setMax((int) finalTime);
               oneTimeOnly = 1;
            }
        
            tx2.setText(String.format("%d min, %d sec",
               TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
               TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
               TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) 
                  finalTime)))
            );

            tx1.setText(String.format("%d min, %d sec",
               TimeUnit.MILLISECONDS.toMinutes((long) startTime),
               TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
               TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) 
                  startTime)))
            );

            seekbar.setProgress((int)startTime);
            myHandler.postDelayed(UpdateSongTime,100);
            b2.setEnabled(true);
            b3.setEnabled(false);
         }
      });

      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Pausing 
               sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.pause();
            b2.setEnabled(false);
            b3.setEnabled(true);
         }
      });

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;

            if((temp+forwardTime)<=finalTime){
               startTime = startTime + forwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped forward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }else{
               Toast.makeText(getApplicationContext(),"Cannot jump forward 5
                  seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });

      b4.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;

            if((temp-backwardTime)>0){
               startTime = startTime - backwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped backward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }else{
               Toast.makeText(getApplicationContext(),"Cannot jump backward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });
   }

   private Runnable UpdateSongTime = new Runnable() {
      public void run() {
         startTime = mediaPlayer.getCurrentPosition();
         tx1.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
            TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
            toMinutes((long) startTime)))
         );
         seekbar.setProgress((int)startTime);
         myHandler.postDelayed(this, 100);
      }
   };
}

Modified Content of XML -> res/layout/activity_main.xml.


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed


Here abc shows the logo of Andro Development.

<?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" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <TextView android:text="Music Palyer" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Andro Development"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:src="@drawable/abc"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/forward"
      android:id="@+id/button"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/pause"
      android:id="@+id/button2"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/back"
      android:id="@+id/button3"
      android:layout_alignTop="@+id/button2"
      android:layout_toRightOf="@+id/button2"
      android:layout_toEndOf="@+id/button2" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/rewind"
      android:id="@+id/button4"
      android:layout_alignTop="@+id/button3"
      android:layout_toRightOf="@+id/button3"
      android:layout_toEndOf="@+id/button3" />

   <SeekBar
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/seekBar"
      android:layout_alignLeft="@+id/textview"
      android:layout_alignStart="@+id/textview"
      android:layout_alignRight="@+id/textview"
      android:layout_alignEnd="@+id/textview"
      android:layout_above="@+id/button" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView2"
      android:layout_above="@+id/seekBar"
      android:layout_toLeftOf="@+id/textView"
      android:layout_toStartOf="@+id/textView" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView3"
      android:layout_above="@+id/seekBar"
      android:layout_alignRight="@+id/button4"
      android:layout_alignEnd="@+id/button4" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="Medium Text"
      android:id="@+id/textView4"
      android:layout_alignBaseline="@+id/textView2"
      android:layout_alignBottom="@+id/textView2"
      android:layout_centerHorizontal="true" />

</RelativeLayout>

Content -> res/values/string.xml.

<resources>
   <string name="app_name">My Application</string>
   <string name="back"><![CDATA[<]]></string>
   <string name="rewind"><![CDATA[<<]]></string>
   <string name="forward"><![CDATA[>>]]></string>
   <string name="pause">||</string>
</resources>

 

Learn More About Android Resources.

Content -> AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.androdevelopment.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.androdevelopment.myapplication.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

Let’s make an effort to run the android mediaplayer application. I suppose you have linked your actual Google android Mobile device with your personal computer. To perform the app from Eclipse, wide open one of your project’s activity data and click Run Eclipse Run icon from the toolbar. Prior to starting your application, Google android studio will screen following screens

android mediaplayer

By default you’ll start to see the pause button unabled/disabled. Now press play button and it could become disable and pause button become enable. Up till now, the music has been participating in. Now press the pause button and start to see the pause notification. That is shown below

android mediaplayer

Now when you press the play button again, the music won’t play right from the start but from where it was paused. Now press the fast front or backward button to leap the song ahead or backward 5 a few moments. A time emerged when the melody cannot be bounce forward. At this time , the notification seems which would be something similar to this

android mediaplayer

Your music would stay playing in the backdrop when you are doing other duties in your mobile. To be able to stop it , you have to leave this software from backdrop activities.

android mediaplayer

Above image shows when you select rewind button.

See Also:

Android JetPlayer

Android AudioManager

Android Audio Capture


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed