Many apps require the feature to add the audio feature in their application and there so many audio files that we have to play inside our application. If we will store so many audio files inside our application, then it will increase the size of the app and this may reduce the user base due to the huge app size. So the better way to tackle this problem is to store the audio files in your database and access them from their unique web URL. In this article, we will take a look at playing an audio file from URL in Android.
What we are going to build in this application?
We will be building a simple application in which we will display two buttons for play and pause of our audio. We will be loading that audio from the URL. Below is the video in which we will get to see what we are going to build in this article. Now let’s move towards the implementation. 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: 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.
Step 3: Adding permissions to the AndroidManifest.xml file
As we are playing audio from URL in android. So we will have to add Internet permissions to load URL. Add below permissions to the AndroidManifest.xml file.
Step 4: 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.
After adding the code now run your app and see the output of the app.
Note: After clicking on the play button wait for some time as we are loading our audio file from the URL. So it will take a little bit of time to load our audio file.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.