Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Play Audio From URL in Android using Jetpack Compose?
Next article icon

How to Play Audio from URL in Android?

Last Updated : 20 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

https://media.geeksforgeeks.org/wp-content/uploads/20210113122113/Screenrecorder-2021-01-13-12-19-24-250.mp4

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.

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 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.

XML

<!-- Permissions of internet -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
                      
                       

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.

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.appcompat.app.AppCompatActivity;
  
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for 
    // button and media player
    Button playBtn, pauseBtn;
    MediaPlayer mediaPlayer;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // 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();
            }
        });
          
        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 = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
          
        // 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);
  
        // below line is use to set our 
        // url to our media player.
        try {
            mediaPlayer.setDataSource(audioUrl);
            // below line is use to prepare
            // and start our media player.
            mediaPlayer.prepare();
            mediaPlayer.start();
  
        } catch (IOException e) {
            e.printStackTrace();
        }
        // below line is use to display a toast message.
        Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
    }
}
                      
                       

After adding the code now run your app and see the output of the app. 

Output:

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. 

https://media.geeksforgeeks.org/wp-content/uploads/20210113122113/Screenrecorder-2021-01-13-12-19-24-250.mp4


Next Article
How to Play Audio From URL in Android using Jetpack Compose?

C

chaitanyamunje
Improve
Article Tags :
  • Android
  • Java
  • Technical Scripter
  • Android Projects
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

  • How to Play Video from URL in Android?
    In this article, you will see how to play a video from a URL on Android. For showing the video in our Android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can p
    3 min read
  • How to Load PDF from URL in Android?
    Most of the apps require to include support to display PDF files in their app. So if we have to use multiple PDF files in our app it is practically not possible to add each PDF file inside our app because this approach may lead to an increase in the size of the app and no user would like to download
    5 min read
  • Play Audio From URL in Android using Kotlin
    Many applications want to add different types of audio files to their android applications. These audio files are played using a media player within the android application. We can play audio files within the android application from different sources by playing audio from a web URL or by simply add
    4 min read
  • How to Play Audio From URL in Android using Jetpack Compose?
    Many apps require the feature to add the audio feature in their application and there are 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 t
    7 min read
  • How to Manage Audio Focus in Android?
    The audio focus in Android needs to be managed and it is one of the important to handle the audio interruptions. In Android, many applications play media simultaneously, and to increase the User Experience the Audio interruptions are handled. For example, if the application is playing Audio, suddenl
    5 min read
  • How to Fetch Audio file From Storage in Android?
    Selecting an audio file from the phone's storage is required when the user is uploading or sending an audio file in your application. So this article primarily focuses on getting the audio files as a URI from your phone's storage. Step by Step Implementation Step 1: Create a New Project To create a
    2 min read
  • How to play an Audio file using Java
    In this article we will see, how can we play an audio file in pure java, here pure means, we are not going to use any external library. You can create your own music player by the help of this article. Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats. There are 2 different in
    4 min read
  • Play Audio in Android using Jetpack Compose
    In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a Media Player, playing, pausing, starting, and stopping the media. In this article, we will show you how
    3 min read
  • How to Build Spotify Clone in Android?
    There are many android applications present in the market which are available to play songs on mobile phones. The famous one of all these music players is Spotify. In this article, we will be building a Spotify clone application using Spotify Web APIs. Step by Step ImplementationStep 1: Create a New
    15+ min read
  • How to Clear or Release Audio Resources in Android?
    As the memory consumption in Android is prioritized more, if the Application is using the Mediaplayer API, most of the memory resources are allocated. The developer needs to take care when the Mediaplayer instance is no longer needed or after completion of playing the media resource file. So in this
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences