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
- Open Android Studio and select "Create New Project".
- Name the project as per your wish and select your activity template.
- 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.
- 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.
- <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>
- appcompat.Light.The dialog is used to apply dialog like the style to an activity.
- 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%.
- In the same way, windowCloseOnTouchOutside is used to handle dialog cancel on touch outside of the views. It is similar setCancelableOnTouchOutside method for dialogs.
- Then open your layout file (for example activity_main.xml) and add the following 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>
- Your layout is shown in the following figure.
- Then click Run to view the output activity as dialog in the following figure.
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 filter will lead the app to be in suggestions when opening/selecting any audio files. The following figure is for your reference.
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…).
- Media Player can be initialized as shown in the following.
- MediaPlayer mp = new MediaPlayer();
- The selected song’s path can be get using Intent and the 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();
- }
- }
- Selected song can be played with start method in media player API.
- Media Player can be paused using the pause method in media player API.
- if (mp.isPlaying()) {
- mp.pause();
- }
- 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.
- Next, we will see, how to get the details of the selected audio file. MediaMetadataRetriever is used here.
- The MediaMetaDataRetriever can be initialized as below.
- metaRetriever = new MediaMetadataRetriever();
- metaRetriever.setDataSource(filePath);
- Song’s album can be retrieved using the following code.
- metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
- Song’s artist can be retrieved using the following code.
- metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
- 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);
- 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();
- }
- }
- The final output is shown in the following screenshot.
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.