Showing posts with label music player. Show all posts

How to Create a Music Previewer in Android

musicpreviewer
Introduction:
In this article, we will learn how to create a music previewer like Google play music and register the app as Music Player to the phone. Registering mobile app as Music Player will show our app in suggestions while opening audio files.
Intent Filter:
Registering app as music player will be achieved by intent-filters in AndroidManifest.xml against our activity. To know more about Intent-Filters, read the link.
Coding Part:
Steps:
I have split this part into 3 steps as in the following.
Step 1: Creating New Project with Empty Activity.
Step 2: Implementation of Music Previewer UI.
Step 3: Setting up Manifest with Intent Filters.
Step 4: Implementation of Music Previewer in Android.
Step 1: Creating New Project with Android Studio
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select your activity template.
  3. Click “finish” button to create new project in Android Studio.
Step 2: Implementation of Music Previewer UI
In this part, we will see how to create a dialog for music previewer.
  1. We will create an activity named as MainActivity.java and we need this activity to be show like Dialog. So, we have add the following lines in styles.xml file.
    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.Dialog">
            <item name="windowNoTitle">true</item>
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
            <item name="windowMinWidthMajor">90%</item>
            <item name="windowMinWidthMinor">90%</item>
            <item name="android:windowCloseOnTouchOutside">false</item>
        </style>
    
    </resources>
  2. Theme.Appcompat.Light.Dialog is used to apply dialog like style to an activity.
  3. By default, the dialog style applied based on children width. To apply full width to the dialog, use windowMinWidthMinor key with value 90%.
  4. In the same way, windowCloseOnTouchOutside is used to handle dialog cancel on touch outside of the views. It is similar setCancelableOnTouchOutside method for dialogs.
  5. Then open your layout file (for example: activity_main.xml) and add the followings lines.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_margin="10dp"
        android:background="@android:color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="10dp"
        tools:context=".MainActivity">
    
            <ImageView
                android:id="@+id/song_art"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:scaleType="fitXY"
                android:contentDescription="@string/image_desc"
                android:src="@mipmap/ic_launcher" />
    
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="9"
                android:orientation="vertical"
                android:paddingLeft="10dp"
                android:paddingStart="10dp"
                tools:ignore="RtlSymmetry">
    
                <TextView
                    android:id="@+id/song_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/tv_song_title" />
    
                <TextView
                    android:id="@+id/song_artist"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:text="@string/tv_song_artist" />
            </LinearLayout>
    
            <ImageView
                android:id="@+id/play_pause"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:contentDescription="@string/image_desc"
                android:src="@drawable/ic_play" />
    
    </LinearLayout>
  6. Your layout shown like in the following figure.
    scrn 1
  7. Then click Run to view the output activity as dialog in the following figure.
scrn 2
Step 3: Setting up manifest with Intent-Filter:
In this step, we will learn How to apply intent-filter to register your music player app. The following line of codes will help us to register the app.
<activity android:name=".MainActivity">
 <intent-filter>
  <action android:name="android.intent.action.MAIN" />

  <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 <intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <data android:scheme="file"/>
  <data android:mimeType="audio/*"/>
 </intent-filter>
</activity>
This filters will lead the app to be in suggestions when we opening/selecting any audio files. The following figure for your reference.
scrn 3
Step 4: Implementation of Music Previewer in Android.
In this step, we will how to handle media options using Media Player API in Android (i.e., play, pause…).
  1. Media Player can be initialized as shown in the following.
    MediaPlayer mp = new MediaPlayer();
  2. The selected song’s path can be get using Intent and activity opening option can be identified with its action.
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
      try {
       assignSongDetails(getIntent().getData().getPath());
       mp.setDataSource(getIntent().getData().getPath());
       mp.prepare();
       mp.start();
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
  3. Selected song can be played with start method in media player API.
    mp.start();
  4. Media Player can be paused using pause method in media player API.
    if (mp.isPlaying()) {
      mp.pause();
     }
     
  5. Then click Run or Shift + F10 to deploy the app in debug mode. Close your app and select any audio file you want to open and select your app. Now you can find your music player works fine.
  6. Next we will see, how to get the details of the selected audio file. MediaMetadataRetriever is used here.
  7. The MediaMetaDataRetriever can be initialized like below.
    metaRetriever = new MediaMetadataRetriever();
     metaRetriever.setDataSource(filePath);
  8. Song’s album can be retrieved using the following code.
    metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
  9. Song’s artist can be retrieved using the following code.
    metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
  10. In the same way, we can read the album art using the following method.
    byte[] art = metaRetriever.getEmbeddedPicture();
     Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
     imgSongArt.setImageBitmap(songImage);
     
  11. The media player can be stopped using stop method in media player API with onPause method of the activity.
    @Override
     protected void onPause() {
      super.onPause();
      assert mp != null;
      if (mp.isPlaying()) {
       mp.stop();
      }
     }
    scrn 4
    Full Code:
    You can find the full code implementation here.
    public class MainActivity extends AppCompatActivity {
    
        TextView tvSongTitle, tvSongArtist;
        ImageView playPause, imgSongArt;
        MediaPlayer mp = new MediaPlayer();
    
        MediaMetadataRetriever metaRetriever;
        byte[] art;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tvSongTitle = findViewById(R.id.song_title);
            tvSongArtist = findViewById(R.id.song_artist);
            playPause = findViewById(R.id.play_pause);
            imgSongArt = findViewById(R.id.song_art);
    
            if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
                try {
                    assignSongDetails(getIntent().getData().getPath());
                    mp.setDataSource(getIntent().getData().getPath());
                    mp.prepare();
                    mp.start();
                    playPause.setImageResource(R.drawable.ic_pause);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            playPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mp.isPlaying()) {
                        mp.pause();
                        playPause.setImageResource(R.drawable.ic_play);
                    } else {
                        mp.start();
                        playPause.setImageResource(R.drawable.ic_pause);
                    }
                }
            });
    
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    playPause.setImageResource(R.drawable.ic_play);
                }
            });
    
        }
    
        void assignSongDetails(String filePath) {
            metaRetriever = new MediaMetadataRetriever();
            metaRetriever.setDataSource(filePath);
            try {
                tvSongTitle.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
                tvSongArtist.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
                try {
                    art = metaRetriever.getEmbeddedPicture();
                    Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
                    imgSongArt.setImageBitmap(songImage);
                } catch (Exception ex) {
                    imgSongArt.setImageResource(R.mipmap.ic_launcher);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            assert mp != null;
            if (mp.isPlaying()) {
                mp.stop();
            }
        }
    }
Download Code:
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.