Android Mediaplayer Example – Play from Internet

In this post, we are going to discuss about how to play a music file(MP3) present over the internet. Android provides extensive support for playing music and it has dedicated a class called MediaPlayer which has all the necessary methods to play, pause, stop and do more with a MP3 file.

With the help of Android MediaPlayer framework we can play audio from media files stored in/as:

  1. Application’s resources (raw resources) [ Android Mediaplayer Example – Play from local resource ]
  2. Standalone files in the filesystem[ Android Mediaplayer Example – Play from URI ]
  3. Data stream arriving over a network connection

Here we will discuss about how we can play music files present over the internet.

[pgsubscribe]

Before we start with developing application, download code from here to follow with the below listings.

As this application requires Internet connectivity to download mp3 file from remote server, it would be good if Internet connectivity check is done before downloading mp3 file from remote server.

Here are the tutorials which talk about checking Wifi/Mobile Internet:

Android Check Wi-Fi Internet Connection
Android Check Mobile Internet Connection

Quick Links

Project Structure

Project creation:

  • Create new android project [File >> New >> Android Project] with project name MusicAndroidActivity2
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.example’
  • Click finish

Code Listings

Layout XML:

Open main.xml present under /res/layout folder and replace the XML with the below one. Here we are going to create two buttons – one for playing music and other for stopping music.

<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="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Playing Music from SD Card"
        android:textSize="20dp" />

    <Button
        android:id="@+id/play"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="Play" />

    <Button
        android:id="@+id/stop"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="Stop" />

</LinearLayout>

How to play audio that’s available over the internet?

  • Look for the music file from internet and I just uploaded a song into my blog (http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3). We are just going to read the data stream arriving over the internet and play it inside the applicaiotn.
  • Create MediaPlayer object:
    	
    MediaPlayer mPlayer new MediaPlayer();
  • Locate the audio file:
    String url = "http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3"; 
  • Set the audio stream type of the media player:
    	
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  • Set the data source as a content Uri:
    	
    try {
    mPlayer.setDataSource(url);
    } catch (IllegalArgumentException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (SecurityException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (IllegalStateException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (IOException e) {
    e.printStackTrace();
    }
  • Prepare the player for playback, synchronously:
    	
    try {
    mPlayer.prepare();
    } catch (IllegalStateException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (IOException e) {
    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    }
  • Start the player:
    	
    mPlayer.start();

That’s it. Let us create a sample application to demonstrate the usage of MediaPlayer to access local resource(Music file) present in the system/device and play it.

Create objects for Media player and buttons right under the MusicAndroidActivity class

	
MediaPlayer mPlayer;
Button buttonPlay;
Button buttonStop;
String url = "http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3"; 

Write listeners for the two buttons we created

Add below code snippets inside onCreate() method so that once the activity is launched, it will listen for button click events.

Button click event listener to play music:

		buttonPlay = (Button) findViewById(R.id.play);
		buttonPlay.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {				 
				mPlayer = new MediaPlayer();
				mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					mPlayer.setDataSource(url);
				} catch (IllegalArgumentException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (SecurityException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (IllegalStateException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					mPlayer.prepare();
				} catch (IllegalStateException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				} catch (IOException e) {
					Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
				}
				mPlayer.start();
			}
		});

Button click event listener to stop music:

		buttonStop = (Button) findViewById(R.id.stop);
		buttonStop.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mPlayer!=null && mPlayer.isPlaying()){
					mPlayer.stop();
				}
			}
		});

Add INTERNET permission as our program is going to read music file as data stream from the internet

 <uses-permission android:name="android.permission.INTERNET" />

We are done with the coding part, let us test the application.

[pglinkadssmall1]

Demo

Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

I hope you enjoyed the post!! :). Do share your comments right away from the comment box below.
[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Tim

    Thanks for the sample & happy new year from London. I guess I need to look at async next.

    Tim

  • varsha

    Thanks .. Android Mediaplayer Example – Play from URI this is not working on Android -LG device version is 4.0.3.. but same is working on Android -Nexus-4.2.

    on LG 4.0.3 getting below errors

    E/MediaPlayer(3484): error (1, 0)

    E/MediaPlayer(3484): Attempt to call getDuration without a valid mediaplayer

    E/MediaPlayer(3484): error (-38, 0)

    E/MediaPlayer(3484): start called in state 0

    E/MediaPlayer(3484): error (-38, 0)

    Can u please check and help me about this issue..

  • cc

    Your code works for me, but when I upload the .mp3 I want to a server and change the URL to play my file, it doesn’t work. I can play my file just fine in a web browser though. Can anyone tell me the problem or how to fix it? My file is at:

    http://soupnutsy.ca/mm/iftomorrowslow.mp3

    • Please check if the server is allowing devices to stream Mp3 file.

      • cc

        I don’t know how I would even find that out. It’s a shared hosting service. I don’t have access to the server settings or anything like that.

        Can you recommend a hosting service that does allow devices to stream Mp3 files? I tried another free hosting service called tindeck.com, but I ran into the same problems.

        • No idea about free service.

          • cc

            Do you know of any reasonably-priced paid hosting services that allow it?

  • Look for the service provider who does well in your geography.

  • hai pham tuan

    I have question, how can i upload my file audio to internet and get that link to play my file, i try to up my google drive and take that link but not working. So can you give me one idea for this problem (tips: i dont have own website, so i dont know where to upload).

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares