Play Audio Using Mp3 File

We can able to play the local mp3 file using mediaplayer class. We gone to work in simple example for get our audio to play using mediaplayer.
Using mediaplayer, we get multiple player functions inside it.

MainActivity.class

In this class, we set our audio file to play using mediaplayer.

    package com.example.codebrigeaudioexample;  
      
    import android.media.MediaPlayer;  
    import android.os.Bundle;  
    import android.os.Environment;  
    import android.app.Activity;  
    import android.view.Menu;  
    import android.view.View;  
    import android.view.View.OnClickListener;  
    import android.widget.Button;  
      
    public class MainActivity extends Activity {  
        Button start,pause,stop;  
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
              
            start=(Button)findViewById(R.id.button1);  
            pause=(Button)findViewById(R.id.button2);  
            stop=(Button)findViewById(R.id.button3);  
            //create  media player  
            final MediaPlayer mp=new MediaPlayer();  
            try{  
                    //you can change the path, externalstorage means sdcard. 
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Ringtones/Ringo.mp3");  
              
            mp.prepare();  
            }catch(Exception e){e.printStackTrace();}  
              
            start.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                    mp.start();  
                }  
            });  
            pause.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                    mp.pause();  
                }  
            });  
            stop.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                    mp.stop();  
                }  
            });  
        }  
    }  

activity_main.xml

This xml file shows three buttons with start,pause and stop for audio play.