Adding Some Media Support to Your Application

Next, let's add some pizzazz to MyFirstAndroidApp by having the application play an MP3 music file.Android media player features are found in the MediaPlayer class of the package.

You can create MediaPlayer objects from existing application resources or by specifying a target file using a Uniform Resource Identifier (URI). For simplicity, we begin by accessing an MP3 using the Uri class from the package.

Some methods in the and classes are shown in Table 3.3.

Table 3.3 Important MediaPlayer and URI Parsing Methods





Creates a new Media Player with a given target to play



Starts media playback



Stops media playback



Releases the resources of the Media Player object


Instantiates a Uri object from an appropriately formatted URI address

To add MP3 playback support to MyFirstAndroidApp, edit the file First,you must add the appropriate import statements for the MediaPlayer class.

import; import;

Next, within the MyFirstAndroidApp class, declare a member variable for your MediaPlayer object. private MediaPlayer mp;

Now, create a new method called playMusicFromWeb() in your class and make a call to this method in your onCreate() method.The playMusicFromWeb() method creates a valid Uri object, creates a MediaPlayer object, and starts the MP3 playing. If the operation should fail for some reason, the method logs a custom error with your logging tag. The playMusicFromWeb() method should look something like this:

public void playMusicFromWeb() { try {

Uri file = Uri.parse(""

+ "/podcasts/PerlgurlPromo.mp3"); mp = MediaPlayer.create(this, file); mp.start();

catch (Exception e) {

Log.e(DEBUG_TAG, "Player failed", e);

And finally, you want to cleanly exit when the application shuts down. To do this, you need to override the onStop() method and stop the MediaPlayer object and release its resources.

In Eclipse, you can right-click within the class and choose Source (or Alt+Shift+S). Choose the option Override/Implement Methods and check the onStop() method.

The onStop() method should look something like this:

protected void onStop() { if (mp != null) { mp.stop(); mp.release();


Now, if you run MyFirstAndroidApp in the emulator (and you have an Internet connection to grab the data found at the URI location), your application plays the MP3.When you shut down the application, the MediaPlayer is stopped and released appropriately.

Was this article helpful?

0 0
Easy Software Profits

Easy Software Profits

Here's How Anyone Can Start, Build and Run their Own Successful Software Empire Without Knowing the First Thing About Programming, Scripting Or Any 'Coder' Stuff. There is no doubt about it software sells. Software has a high percieved value and it solves problems for people.  A claim that can't always be made for PDF books, Video products and the like.

Get My Free Ebook

Post a comment