How to Create a Dynamic Audio Player in Android with Firebase Realtime Database?
Last Updated :
22 Dec, 2022
Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implementing a dynamic audio player in our Android app.Â
What we are going to build in this article?Â
In this article, we will be building a simple application in which we will be playing an audio file from a web URL and we will be changing that audio file URL in runtime to update our audio file. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.Â
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase Â
After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Â

Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. Â

After completing this process you will get to see the below screen. Â

Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle (app) file and make sure that the below dependency is added in your dependencies section. Â
implementation 'com.google.firebase:firebase-database:19.6.0'
After adding this dependency add the dependency of ExoPlayer in your Gradle file. Â
Step 3: Adding permission for the Internet Â
As we are loading our video from the internet so we have to add permissions for the Internet in the Manifest file. Navigate to the app > AndroidManifest.xml file and add the below permissions in it. Â
XML
<!--Permissions for internet-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context=".MainActivity">
<!--Button for playing audio-->
<Button
android:id="@+id/idBtnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Play Audio file"
android:textAllCaps="false" />
<!--Button for pausing the audio-->
<Button
android:id="@+id/idBtnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/idBtnPlay"
android:layout_centerInParent="true"
android:text="Pause Audio"
android:textAllCaps="false" />
</RelativeLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
// creating a variable for
// button and media player
Button playBtn, pauseBtn;
MediaPlayer mediaPlayer;
// creating a string for storing
// our audio url from firebase.
String audioUrl;
// creating a variable for our Firebase Database.
FirebaseDatabase firebaseDatabase;
// creating a variable for our
// Database Reference for Firebase.
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// below line is used to get the instance
// of our Firebase database.
firebaseDatabase = FirebaseDatabase.getInstance();
// below line is used to get reference for our database.
databaseReference = firebaseDatabase.getReference("url");
// calling add value event listener method for getting the values from database.
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// this method is call to get the realtime updates in the data.
// this method is called when the data is changed in our Firebase console.
// below line is for getting the data from snapshot of our database.
audioUrl = snapshot.getValue(String.class);
// after getting the value for our audio url we are storing it in our string.
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// calling on cancelled method when we receive any error or we are not able to get the data.
Toast.makeText(MainActivity.this, "Fail to get audio url.", Toast.LENGTH_SHORT).show();
}
});
// initializing our buttons
playBtn = findViewById(R.id.idBtnPlay);
pauseBtn = findViewById(R.id.idBtnPause);
// setting on click listener for our play and pause buttons.
playBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calling method to play audio.
playAudio(audioUrl);
}
});
pauseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// checking the media player
// if the audio is playing or not.
if (mediaPlayer.isPlaying()) {
// pausing the media player if
// media player is playing we are
// calling below line to stop our media player.
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
// below line is to display a message when media player is paused.
Toast.makeText(MainActivity.this, "Audio has been paused", Toast.LENGTH_SHORT).show();
} else {
// this method is called when media player is not playing.
Toast.makeText(MainActivity.this, "Audio has not played", Toast.LENGTH_SHORT).show();
}
}
});
}
private void playAudio(String audioUrl) {
// initializing media player
mediaPlayer = new MediaPlayer();
// below line is use to set the audio stream type for our media player.
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
// below line is use to set our
// url to our media player.
mediaPlayer.setDataSource(audioUrl);
// below line is use to prepare
// and start our media player.
mediaPlayer.prepare();
mediaPlayer.start();
// below line is use to display a toast message.
Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// this line of code is use to handle error while playing our audio file.
Toast.makeText(this, "Error found is " + e, Toast.LENGTH_SHORT).show();
}
}
}
Step 6: Adding URL for your audio file in Firebase Console Â
For adding audio URL in Firebase Console. Browse for Firebase in your browser and Click on Go to Console option in the top right corner as shown in the below screenshot. Â

 After clicking on Go to Console option you will get to see your project. Click on your project name from the available list of projects.Â

After clicking on your project. Click on the Realtime Database option in the left window. Â

After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen. Â

In this project, we are adding our rules as true for reading as well as write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.
Inside Firebase Realtime Database. Navigate to the Data tab. Inside this tab on the database section click on the "+" icon. After clicking on the "+" icon you will get to see two input fields which are the Name and Value fields. Inside the Name field, you have to add the reference for your video file which in our case is "url". And in our value field, we have to add the URL for our audio file. After adding the value in this field. Click on the Add button and your data will be added to Firebase Console. Â

After adding the URL for your video. Now run your app and see the output of the app below:Â
Output:
You can change the URL of your audio dynamically.Â
Similar Reads
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading
8 min read
How to Create Dynamic WebView in Android with Firebase?
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView which we have to load. So if you are looking for loading
6 min read
How to Create Dynamic PDF Viewer in Android with Firebase?
If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. For loading this PDF from the server we prefer to use PDF Viewer which will load the PDF from the URL in Androi
7 min read
How to Save Data to the Firebase Realtime Database in Android?
Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simp
7 min read
User Authentication and CRUD Operation with Firebase Realtime Database in Android
Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for the backend database and handling the database. In this article, we will take a look at the implementation of t
15+ min read
How to Delete Data from Firebase Realtime Database in Android?
In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase. Â What we are going to build in this article? Â We will be showing a simple AlertBox when the user long clicks on the ite
4 min read
Firebase RealTime Database with Operations in Android with Examples
Firebase Realtime Database is a Cloud hosted database, i.e. it runs on a cloud and access to the user is provided as a service. It stores data in JSON (Javascript Object Notation) format, a format to store or transport data. All the users connected to it can get access to the data at Real Time. Feat
6 min read
How to Retrieve Data from Firebase Realtime Database in Android ListView?
Firebase Realtime Database provides us a feature to give Real-time updates to your data inside your app within milli-seconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at the implementation of the Firebase Realtime Database for o
7 min read
How to Retrieve Data from the Firebase Realtime Database in Android?
Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is for its Firebase Realt
5 min read
How to Retrieve PDF File From Firebase Realtime Database in Android?
When we are creating an Android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from Firebase. Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It
7 min read