How To Create A Music Previewer In Android

Android
 

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 apps as Music Player will show our app in suggestions while opening audio files.
 

Intent Filter

 
Registering an app as a music player will be achieved by intent-filters in AndroidManifest.xml against our activity. To know more about Intent-Filters, read the link.
 
Steps
 
I have split this part into 4 steps as in the following.
  • Step 1 - Creating a 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 a New Project with Android Studio
  1. Open Android Studio and select "Create New Project".
  2. Name the project as per your wish and select your activity template.
     
    Android
     
  3. Click the Finish button to create the new project in Android Studio.
Step 2 - Implementation of Music Previewer UI
 
In this part, we will see how to create a dialog for the music previewer.
  1. We will create an activity named java and we need this activity to be shown as a dialog. So, we have added the following lines in styles.xml file.
    1. <resources>  
    2.   
    3.     <!-- Base application theme. -->  
    4.     <style name="AppTheme" parent="Theme.AppCompat.Light.Dialog">  
    5.         <item name="windowNoTitle">true</item>  
    6.         <item name="colorPrimary">@color/colorPrimary</item>  
    7.         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>  
    8.         <item name="colorAccent">@color/colorAccent</item>  
    9.         <item name="windowMinWidthMajor">90%</item>  
    10.         <item name="windowMinWidthMinor">90%</item>  
    11.         <item name="android:windowCloseOnTouchOutside">false</item>  
    12.     </style>  
    13.   
    14. </resources>  
  1. appcompat.Light.The dialog is used to apply dialog like the style to an activity.
  2. By default, the dialog style applied based on children's width. To apply the full width to the dialog, use the windowMinWidthMinor key with value 90%.
  3. In the same way, windowCloseOnTouchOutside is used to handle dialog cancel on touch outside of the views. It is similar setCancelableOnTouchOutside method for dialogs.
  4. Then open your layout file (for example activity_main.xml) and add the following lines.
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     xmlns:tools="http://schemas.android.com/tools"  
    4.     android:layout_width="match_parent"  
    5.     android:layout_height="70dp"  
    6.     android:layout_margin="10dp"  
    7.     android:background="@android:color/white"  
    8.     android:gravity="center_vertical"  
    9.     android:orientation="horizontal"  
    10.     android:padding="10dp"  
    11.     tools:context=".MainActivity">  
    12.   
    13.         <ImageView  
    14.             android:id="@+id/song_art"  
    15.             android:layout_width="60dp"  
    16.             android:layout_height="60dp"  
    17.             android:scaleType="fitXY"  
    18.             android:contentDescription="@string/image_desc"  
    19.             android:src="@mipmap/ic_launcher" />  
    20.   
    21.         <LinearLayout  
    22.             android:layout_width="0dp"  
    23.             android:layout_height="wrap_content"  
    24.             android:layout_weight="9"  
    25.             android:orientation="vertical"  
    26.             android:paddingLeft="10dp"  
    27.             android:paddingStart="10dp"  
    28.             tools:ignore="RtlSymmetry">  
    29.   
    30.             <TextView  
    31.                 android:id="@+id/song_title"  
    32.                 android:layout_width="match_parent"  
    33.                 android:layout_height="wrap_content"  
    34.                 android:text="@string/tv_song_title" />  
    35.   
    36.             <TextView  
    37.                 android:id="@+id/song_artist"  
    38.                 android:layout_width="match_parent"  
    39.                 android:layout_height="wrap_content"  
    40.                 android:layout_marginTop="10dp"  
    41.                 android:text="@string/tv_song_artist" />  
    42.         </LinearLayout>  
    43.   
    44.         <ImageView  
    45.             android:id="@+id/play_pause"  
    46.             android:layout_width="40dp"  
    47.             android:layout_height="40dp"  
    48.             android:contentDescription="@string/image_desc"  
    49.             android:src="@drawable/ic_play" />  
    50.   
    51. </LinearLayout>  
  1. Your layout is shown in the following figure.
     
    Android
  1. Then click Run to view the output activity as dialog in the following figure.
     
    Android
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.
  1. <activity android:name=".MainActivity">  
  2.     <intent-filter>  
  3.         <action android:name="android.intent.action.MAIN" />  
  4.   
  5.         <category android:name="android.intent.category.LAUNCHER" />  
  6.     </intent-filter>  
  7.     <intent-filter>  
  8.         <action android:name="android.intent.action.VIEW" />  
  9.         <category android:name="android.intent.category.DEFAULT" />  
  10.         <data android:scheme="file"/>  
  11.         <data android:mimeType="audio/*"/>  
  12.     </intent-filter>  
  13. </activity>  
This filter will lead the app to be in suggestions when opening/selecting any audio files. The following figure is for your reference.
 
Android
 
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.
    1. MediaPlayer mp = new MediaPlayer();  
  1. The selected song’s path can be get using Intent and the activity opening option can be identified with its action.
    1. if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {  
    2.     try {  
    3.         assignSongDetails(getIntent().getData().getPath());  
    4.         mp.setDataSource(getIntent().getData().getPath());  
    5.         mp.prepare();  
    6.         mp.start();  
    7.     } catch (Exception e) {  
    8.         e.printStackTrace();  
    9.     }  
    10. }  
  1. Selected song can be played with start method in media player API.
    1. mp.start();  
  1. Media Player can be paused using the pause method in media player API.
    1. if (mp.isPlaying()) {  
    2.     mp.pause();  
    3. }  
  1. 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.
  2. Next, we will see, how to get the details of the selected audio file. MediaMetadataRetriever is used here.
  3. The MediaMetaDataRetriever can be initialized as below.
    1. metaRetriever = new MediaMetadataRetriever();  
    2. metaRetriever.setDataSource(filePath);  
  1. Song’s album can be retrieved using the following code.
    1. metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);  
  1. Song’s artist can be retrieved using the following code.
    1. metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);  
  1. In the same way, we can read the album art using the following method.
    1. byte[] art = metaRetriever.getEmbeddedPicture();  
    2. Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);  
    3. imgSongArt.setImageBitmap(songImage);  
  1. The media player can be stopped using stop method in media player API with onPause method of the activity.
    1. @Override  
    2. protected void onPause() {  
    3.     super.onPause();  
    4.     assert mp != null;  
    5.     if (mp.isPlaying()) {  
    6.         mp.stop();  
    7.     }  
    8. }  
  1. The final output is shown in the following screenshot.
     
    Android
     
Full Code
 
You can find the full code implementation here.
  1. public class MainActivity extends AppCompatActivity {  
  2.   
  3.     TextView tvSongTitle, tvSongArtist;  
  4.     ImageView playPause, imgSongArt;  
  5.     MediaPlayer mp = new MediaPlayer();  
  6.   
  7.     MediaMetadataRetriever metaRetriever;  
  8.     byte[] art;  
  9.   
  10.     @Override  
  11.     protected void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.activity_main);  
  14.   
  15.         tvSongTitle = findViewById(R.id.song_title);  
  16.         tvSongArtist = findViewById(R.id.song_artist);  
  17.         playPause = findViewById(R.id.play_pause);  
  18.         imgSongArt = findViewById(R.id.song_art);  
  19.   
  20.         if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {  
  21.             try {  
  22.                 assignSongDetails(getIntent().getData().getPath());  
  23.                 mp.setDataSource(getIntent().getData().getPath());  
  24.                 mp.prepare();  
  25.                 mp.start();  
  26.                 playPause.setImageResource(R.drawable.ic_pause);  
  27.             } catch (Exception e) {  
  28.                 e.printStackTrace();  
  29.             }  
  30.         }  
  31.   
  32.         playPause.setOnClickListener(new View.OnClickListener() {  
  33.             @Override  
  34.             public void onClick(View view) {  
  35.                 if (mp.isPlaying()) {  
  36.                     mp.pause();  
  37.                     playPause.setImageResource(R.drawable.ic_play);  
  38.                 } else {  
  39.                     mp.start();  
  40.                     playPause.setImageResource(R.drawable.ic_pause);  
  41.                 }  
  42.             }  
  43.         });  
  44.   
  45.         mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {  
  46.             public void onCompletion(MediaPlayer mp) {  
  47.                 playPause.setImageResource(R.drawable.ic_play);  
  48.             }  
  49.         });  
  50.   
  51.     }  
  52.   
  53.     void assignSongDetails(String filePath) {  
  54.         metaRetriever = new MediaMetadataRetriever();  
  55.         metaRetriever.setDataSource(filePath);  
  56.         try {  
  57.             tvSongTitle.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));  
  58.             tvSongArtist.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));  
  59.             try {  
  60.                 art = metaRetriever.getEmbeddedPicture();  
  61.                 Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);  
  62.                 imgSongArt.setImageBitmap(songImage);  
  63.             } catch (Exception ex) {  
  64.                 imgSongArt.setImageResource(R.mipmap.ic_launcher);  
  65.             }  
  66.         } catch (Exception e) {  
  67.             e.printStackTrace();  
  68.         }  
  69.   
  70.     }  
  71.   
  72.     @Override  
  73.     protected void onPause() {  
  74.         super.onPause();  
  75.         assert mp != null;  
  76.         if (mp.isPlaying()) {  
  77.             mp.stop();  
  78.         }  
  79.     }  
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.