Home ANDROID APP Music Player android app in android studio with source code

Music Player android app in android studio with source code

19

The Android platform provides resources for handling media playback, which your apps can use to create an Music player interface between the user and their music files. In this tutorial series, we will create a basic Music player application for Android.

Music Player app will present a list of songs on the user Music player device, so that the user can select songs to play. The app will also present controls for interacting with playback and will continue playing when the user moves away from the app, with a notification displayed while playback elapses.

Create News Android Application with Android Studio : Click Here


Looking for a Quick Solution?
If you’re looking for a quick solution, there’s a great collection of Android app templates over at Market.

In particular, this Android Music Player app template is a great way to get started with building your own app. “Lite Music” is a premium player app template in Android, with a clean interface, that’s simple and elegant to use.

MainActivity.java

package com.dude.musicapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button play,pause,stop;
    MediaPlayer mediaPlayer;
    int pausePosition;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        play=(Button)findViewById(R.id.play);
        pause=(Button)findViewById(R.id.pause);
        stop=(Button)findViewById(R.id.stop);

        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.play:
                if(mediaPlayer==null) {
                    mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song );
                    mediaPlayer.start();
                } else if (!mediaPlayer.isPlaying()) {

                    mediaPlayer.seekTo(pausePosition);
                    mediaPlayer.start();
                }

                break;
            case R.id.pause:
                if(mediaPlayer!=null){
                    mediaPlayer.pause();
                    pausePosition=mediaPlayer.getCurrentPosition();
                }

                break;
            case R.id.stop:
                if(mediaPlayer!=null) {
                    mediaPlayer.stop();
                    mediaPlayer=null;
                }
                break;
        }
    }
}

Introduction


Building the music player will involve using the Content Resolver class to retrieve tracks on the device, the Media Player class to play audio and the Media Controller class to control playback.

Also use a Service instance to play audio when the user is not directly interacting with the app. You should be able to complete this series if you’re an intermediate Android developer, so if you’ve already built a few apps, then this series shouldn’t be a problem for you. Here is a preview of the final app:

<img width=

In this tutorial, we will create the app and query the user device for audio files using the Content Resolver and Cursor classes. In the next part, we will use an Adapter instance to present the songs in a list view, starting playback when the user taps an item from the list. In the final installment of this series, we’ll use the Media Controller class to give the user control over playback, implement functions to skip forward and back, and include a shuffle function.

After this series, we will explore other aspects of media playback that can enhance the app, such as handling audio focus, presenting media files in different ways, and playing streaming media.

Create and Configure a New Project

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/color"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="61dp"
        android:text="Music App"
        android:textColor="#000000"
        android:textSize="40dp" />

    <ImageView
        android:layout_width="220dp"
        android:layout_height="220dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="134dp"
        android:src="@drawable/musiclogo" />

    <Button
        android:id="@+id/play"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="135dp"
        android:background="@drawable/ic_play_circle_filled_black_24dp" />

    <Button
        android:id="@+id/pause"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignBaseline="@+id/play"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="97dp"
        android:background="@drawable/ic_pause_circle_filled_black_24dp" />

    <Button
        android:id="@+id/stop"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignTop="@+id/pause"
        android:layout_alignParentRight="true"
        android:layout_marginTop="-1dp"
        android:layout_marginRight="99dp"
        android:background="@drawable/ic_stop_black_24dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="72dp"
        android:layout_marginLeft="72dp"
        android:layout_marginBottom="213dp"
        android:text="Latest Song play Now Enjoy!"
        android:textColor="#000000"
        android:textSize="20sp" />
</RelativeLayout>


1. Step


Make a Music Player Android project. If you are using Eclipse, then let the IDE (Integrated Development Environment) create a main Activity class and layout file for you. For some of the code we use in the series, you will need a minimum API level of 16, so you will need to take additional steps to support older versions. Once your project is created, open the project’s Manifest file. Inside the manifest element, add the following permission:

Again Now stick to portrait orientation for simplicity. The launchMode will aid the process of navigating back to the app after moving away from it. We will display a notification indicating the song currently being played, tapping the notification will take the user back to the app. We are also going to use a Service class for music playback. Add the following line to the project’s Manifest inside the application element and after the activity element:

Alter the package name to suit your own and change the class name if you wish.

Manifest File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dude.musicapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2.Step


Open the project’s main layout file and replace its contents with the following layout: Query the Device for Songs


Let’s query the user’s device for audio files. First, add a new class to your project, naming it Song. We will use this class to model the data for a single audio file. Inside the class declaration, add three instance variables for the data we want to store for each track:Music player.

Feel free to amend the layout to suit your preferences. Each song in the list will be represented by title and artist text strings, so we will use the TextViews to display this data. Notice that the LinearLayout opening tag lists an onClick attribute. We will use this method in the main Activity class to respond to user taps on the songs in the list, playing the song represented by the list item that was tapped.

gradle.app

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.dude.musicapp"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

3. Step 3


Now We will use an Adapter to map the songs to the Music player list view. Add a new class to your app, naming it SongAdapter or another name of your choice. When creating the class, give it the superclass android.widget.BaseAdapter. Eclipse should insert the following outline:

When you run the app, it should present the list of songs on the device, clicking them will cause the app to throw an exception at the moment, but we will implement the click handler in the next tutorial.

Make Browser App. Click Here

Conclusion


We’ve now set the app up to read songs from Music player the user device. In the next part, we will begin playback when the user selects a song using the Media Player class. We will implement playback using a Service class so that it will continue as the user interacts with other apps. Finally, we will use a Media Controller class to give the user control over playback.

YouTube Video

https://youtu.be/1QSkQrkkYzg

If you’re ever in need of extra help with your Android app development projects, you can find experienced Android developers on Envato Studio to help you with everything from UI design to creating a native Android app.

Download Source Code

Click below to get the full source code android Music Player application.

Conclusion

We have successfully created a Music App Android application using Android Studio.


Cheers!

READ MORE…