Monday, 29 April 2013

Audio Player in android


* Live Audio streaming:*

This example has been prepared to stream any audio file from specific URL, and when I have been created this example, I used Android 2.2.
In this sample, I have used one activity, is implemented four interfaces, again. These are:
1. OnClickListener : onClick() method is used, when one of the button has been pushed.
2. OnTouchListener : onTouch() method is used for seeking audio.
3. OnCompletionListener : To set enable of  the buttons, overriden onCompletion() method is just used.
4. OnBufferingUpdateListener : onBufferingUpdate() method is used to update secondary progress of the seekBar instance.


Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/darker_gray">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:textColor="@android:color/black"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_play"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="play" >
        </Button>

        <Button
            android:id="@+id/btn_pause"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="pause" >
        </Button>

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="stop" >
        </Button>
    </LinearLayout>

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp" >
    </SeekBar>

</LinearLayout>


 StreamAudioFromUrlSampleActivity:
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar; 

public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
       private Button btn_play,
       btn_pause,
       btn_stop;
       private SeekBar seekBar;
       private MediaPlayer mediaPlayer;
       private int lengthOfAudio;
       private final String URL = "AudioUrl";


       private final Handler handler = new Handler();
       private final Runnable r = new Runnable()
       {     
              @Override
              public void run() {
                     updateSeekProgress();                                 
              }
       };

       @Override
       public void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              initialize_Controls();
       }

       private void initialize_Controls()
       {
              btn_play = (Button)findViewById(R.id.btn_play);
              btn_play.setOnClickListener(this);
              btn_pause = (Button)findViewById(R.id.btn_pause);
              btn_pause.setOnClickListener(this);
              btn_pause.setEnabled(false);
              btn_stop = (Button)findViewById(R.id.btn_stop);
              btn_stop.setOnClickListener(this);
              btn_stop.setEnabled(false);

              seekBar = (SeekBar)findViewById(R.id.seekBar);
              seekBar.setOnTouchListener(this);

              mediaPlayer = new MediaPlayer();
              mediaPlayer.setOnBufferingUpdateListener(this);
              mediaPlayer.setOnCompletionListener(this);

       }

       @Override
       public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent)
       {
              seekBar.setSecondaryProgress(percent);
       }

       @Override
       public void onCompletion(MediaPlayer mp)
       {
              btn_play.setEnabled(true);
              btn_pause.setEnabled(false);
              btn_stop.setEnabled(false);
       }

       @Override
       public boolean onTouch(View v, MotionEvent event)
       {
              if (mediaPlayer.isPlaying())
              {
                     SeekBar tmpSeekBar = (SeekBar)v;
                     mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
              }
              return false;
       }

       @Override
       public void onClick(View view)
       {

              try
              {                         
                     mediaPlayer.setDataSource(URL);
                     mediaPlayer.prepare();
                     lengthOfAudio = mediaPlayer.getDuration();                   
             
              }
              catch (Exception e)
              {
                     //Log.e("Error", e.getMessage());
              }

              switch (view.getId())
              {
              case R.id.btn_play:              
                     playAudio();
                     break;
              case R.id.btn_pause:
                     pauseAudio();
                     break;
              case R.id.btn_stop:
                     stopAudio();
                     break;
              default:
                     break;
              }

              updateSeekProgress();
       }

       private void updateSeekProgress()
       {
              if (mediaPlayer.isPlaying())
              {
                     seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
                     handler.postDelayed(r, 1000);
              }
       }

       private void stopAudio()
       {
              if(mediaPlayer!=null)
              {
                     mediaPlayer.stop();
              }
              btn_play.setEnabled(true);
              btn_pause.setEnabled(false);
              btn_stop.setEnabled(false);
              seekBar.setProgress(0);
       }

       private void pauseAudio()
       {
              if(mediaPlayer!=null)
              {
                     mediaPlayer.pause();
              }
              btn_play.setEnabled(true);
              btn_pause.setEnabled(false);
       }

       private void playAudio()
       {
              if(mediaPlayer!=null)
              {
                     mediaPlayer.start();
              }            
              btn_play.setEnabled(false);
              btn_pause.setEnabled(true);
              btn_stop.setEnabled(true);
       }
}


Stream Audio from Resources:  Put audio.mp3 file in raw folder of your project.*

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/btn_resource"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txt"
        android:text="@string/resource" >
    </Button>

    <LinearLayout
        android:id="@+id/mediaController"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

StreamAudioFromRecourcesSampleActivity:

import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.RelativeLayout;


public class StreamAudioFromRecourcesSampleActivity extends Activity implements MediaPlayerControl, OnClickListener, OnCompletionListener, OnPreparedListener, OnTouchListener {
    private RelativeLayout rl;
       private Button btn_resource;
    private MediaPlayer mp;
    private MediaController mc;
       private final int AUDIO = R.raw.audio;  
       private boolean isPlayed = false;
      
      
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       
       
        init();
    }

       private void init() {
              // linear layout
              rl = (RelativeLayout)findViewById(R.id.main);
              rl.setOnTouchListener(this); // if touch the screen when playing the audio,
                                                               // the MediaController will be shown.
             
              // play audio button for resource audio
              btn_resource = (Button)findViewById(R.id.btn_resource);
              btn_resource.setOnClickListener(this);
             
              // media player
              mp = new MediaPlayer();
              mp.setOnCompletionListener(this);
              mp.setOnPreparedListener(this);
             
              // madia controller
              mc = new MediaController(this);
              mc.setAnchorView(findViewById(R.id.mediaController));
              mc.setMediaPlayer(this);         
             
             
       }

       private void playMedia() throws IllegalStateException, IOException
       {
              if (isPlayed)
              {                   
                     start();
              }
              else
              {
                     mp.setDataSource(getResources().openRawResourceFd(AUDIO).getFileDescriptor());
                     mp.prepare();
              }
       }
      
       @Override
       public void onClick(View v)
       {
              try
              {                   
                     playMedia();
                     setButtonEnabled(false);
              }
              catch (Exception e)
              {
                     e.printStackTrace();
              }
       }
         @Override
       public void onPrepared(MediaPlayer mp)
       {
              mp.start();
              mc.show();
              isPlayed = false;
       }
      
       @Override
       public void onCompletion(MediaPlayer arg0)
       {
              setButtonEnabled(true);
              isPlayed = true;
              mc.show();
       }
      
       private void setButtonEnabled(boolean b)
       {
              // when playing, not to push button again
              btn_resource.setEnabled(b);      
       }
       @Override
       public boolean onTouch(View v, MotionEvent event)
       {
              if (mc != null)
              {
                     mc.show();
              }
              return false;
       }

       @Override
       public boolean canPause() {return true;  }

       @Override
       public boolean canSeekBackward() {return false; }

       @Override
       public boolean canSeekForward() {return false;}

       @Override
       public int getBufferPercentage()
       {
              int percentage = (mp.getCurrentPosition() * 100) / mp.getDuration();
              return percentage;
       }

       @Override
       public int getCurrentPosition() { return mp.getCurrentPosition();   }

       @Override
       public int getDuration() {return mp.getDuration();}

       @Override
       public boolean isPlaying() {return mp.isPlaying();}

       @Override
       public void pause() {mp.pause();  }

       @Override
       public void seekTo(int pos) {mp.seekTo(pos);}

       @Override
       public void start() {mp.start();mc.show();}
      
       @Override
    protected void onDestroy()
       {
        super.onDestroy();
        mp.stop();
        mp.release();
    }

}

    

No comments:

Post a Comment