Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create the media player in android?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 143
    Comment on it

    If you are looking to create a music layer in android , here is the simple code snippet that can help you for this :-

    Step 1:- Create an xml file for music player say"music_player.xml"

      <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="com.africantunes.MediaPlayer.MusicPlayerTwo">
           <ImageView
              android:id="@+id/song_image"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_alignParentTop="true"
              android:scaleType="centerInside"
              android:background="@drawable/playon"
              android:layout_above="@+id/controls_layout"/>
           <LinearLayout
              android:layout_alignParentBottom="true"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_gravity="center_horizontal"
              android:background="@drawable/rounded_corner"
              android:gravity="center"
              android:orientation="horizontal"
              android:padding="@dimen/padding_10dp"
              android:id="@+id/controls_layout">
               <ImageButton
                 android:id="@+id/btnPrevious"
               android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_marginLeft="@dimen/padding_10dp"
                 android:layout_marginRight="@dimen/padding_10dp"
                 android:background="@null"
                 android:src="@drawable/icon_back" />
               <ImageButton
                 android:id="@+id/btnPlay"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_marginLeft="@dimen/padding_10dp"
                 android:layout_marginRight="@dimen/padding_10dp"
                 android:background="@null"
                 android:src="@drawable/pause_green" />
              <ImageButton
                 android:id="@+id/btnNext"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_marginLeft="@dimen/padding_10dp"
                 android:background="@null"
                 android:src="@drawable/icon_next" />
             </LinearLayout>
       </RelativeLayout>
    

    Step 2:- create certain functions on your main Activity :-

    (a):- function to initialize widgets

      private void initialisingWidgets()
        {
         songLoadingBar = (ProgressBar) findViewById(R.id.song_loading_progress);
         btnPlay = (ImageButton) findViewById(R.id.btnPlay);
         btnNext = (ImageButton) findViewById(R.id.btnNext);
         btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
    
     btnPlay.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View arg0) {
          if (mp.isPlaying()) {
             if (mp != null) {
                   mp.pause();
                   btnPlay.setImageResource(R.drawable.play_green);
              }
           } 
         else {
            if (mp != null) {
               mp.start();
               btnPlay.setImageResource(R.drawable.player_pause);
             }
          }
      }});
    
    
      btnNext.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View arg0) {
        if (currentSongIndex < (songsList.size() - 1)){
           currentSongIndex = currentSongIndex + 1;
         } 
        else{
         currentSongIndex = 0;
         }
       initializeMediaPlayer();
       playSongAsynctask = new PlaySongAsynctask( currentSongIndex);
       playSongAsynctask.execute();
       } });
    
    
      btnPrevious.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View arg0) {
         if (currentSongIndex > 0){
           currentSongIndex = currentSongIndex - 1;
          }
         else{
           currentSongIndex = songsList.size() - 1;
          }
        initializeMediaPlayer();
        playSongAsynctask = new PlaySongAsynctask( currentSongIndex);
        playSongAsynctask.execute();
        }});
    }
    

    (b):- Initialize media player:-

    public void initializeMediaPlayer()
         {
           if (mp != null){
               mp.stop();
               mp.release();
               mp = null;
               mp = new MediaPlayer();
            }
           else{
          mp = new MediaPlayer();
        }
    
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp){
            mp.stop();
            mp.release();
            mp = null;
            if (currentSongIndex < (songsList.size() - 1)){
              if (!isErrorInUri) {
                currentSongIndex = currentSongIndex + 1;
               }
               else{
                  if (!isErrorInUri) {currentSongIndex = 0};
               }
             } 
             playSongAsynctask = new PlaySongAsynctask( currentSongIndex);
             playSongAsynctask.execute();
         }});
      }
    

    (c):- Prepare the mediaPlayer, in background and play song:-

      private class PlaySongAsynctask extends AsyncTask<Void, String, Void> 
         {
       String url;
    
       public PlaySongAsynctask( int songIndex) 
        {
            initializeMediaPlayer();
            url = songsList.get(songIndex);
        }
    
        @Override
        protected void onPreExecute() {
         super.onPreExecute();
         songLoadingBar.setVisibility(View.VISIBLE);
        }
    
    
        @Override
        protected Void doInBackground(Void... params) {
         try 
          {
            isErrorInUri = false;
            mp.setDataSource(MusicPlayerTwo.this, Uri.parse(url));
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
               @Override
               public void onPrepared(MediaPlayer mp) {
               songLoadingBar.setVisibility(View.GONE);
               mp.start();} });
            mp.prepare();
          } 
         catch (FileNotFoundException e) 
          {
            System.out.println("Exception" + e);
            e.printStackTrace();
            runOnUiThread(new Runnable() {
               @Override
                public void run() {
                  dialog = MyUtility.errorMessageAlert(MusicPlayer.this, getResources().getString(R.string.uri_exception_msg));}
            }});
          } 
        return null;
     }
    

    Step 3:- Integrate all the function created on step 2 into OnCreate() method of your activity.

     setContentView(R.layout.music_player);
     initializeMediaPlayer();
     initialisingWidgets();
     initializeMediaPlayer();
       for(int i=0;i<5;i++)
         {
           songsList.add("http://...........song1.mp4");
         }
     playSongAsynctask = new PlaySongAsynctask(currentSongIndex);
     playSongAsynctask.execute();
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: