Using the Audio Media Player API

Posted on Jan 2, 2010 (4 years ago). Seen 35,062 times. 24 comments. Permalink Feed
Member since Dec 23, 2009
Location: Oakland
Stream Posts: 0
Tagged as: Android Tutorial

In this demo, we work with the audio media player API to play a raw media file and can also be used for streaming media.

Most importantly is the creation of the media player instance MediaPlayer player = MediaPlayer.create(this.context, media source). Use of the various player instance methods like player.play() or player.pause() to do as they suggest to play and pause the media playback.

The AudioDemo is straight forward creating the layout and listening to the button click events and response accordingly. When the audiodemo starts note the change of the button change from "Play" to "Stop" and when the demo is paused a return of button text to "Play" Added a toast message to notify the user what is going on.

Note:
The onPause() method is overrided to give playerback control to this instance.
In the res folder, created a raw folder to keep the raw media files in this case robotrack.mp3 (called by R.raw.robotrack)and other types of raw media files. Feel free to drop any type of audio media files but dont forget to change the reference of the files in the Audio Activity.
Always release the media instance back to system in this i.e. player.release();

A good resource about the various media player states, methods and corresponding state diagrams is http://developer.android.com/reference/android/media/MediaPlayer.html


AudioDemo.java
Code:
package org.example.audio;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AudioDemo extends Activity implements OnClickListener {
private static final String TAG = "AudioDemo";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";

MediaPlayer player;
Button playerButton;

public void onClick(View v) {
Log.d(TAG, "onClick: " + v);
if (v.getId() == R.id.play) {
playPause();
}
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

player = MediaPlayer.create(this, R.raw.robotrock);
player.setLooping(false); // Set looping

// Get the button from the view
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop_label);
playerButton.setOnClickListener(this);

// Begin playing selected media
demoPlay();

// Release media instance to system
player.release();

}

@Override
public void onPause() {
super.onPause();
player.pause();
}

// Initiate media player pause
private void demoPause(){
player.pause();
playerButton.setText(R.string.play_label);
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, notPlaying);
}

// Initiate playing the media player
private void demoPlay(){
player.start();
playerButton.setText(R.string.stop_label);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, isPlaying);
}

// Toggle between the play and pause
private void playPause() {
if(player.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
}



main.xml

Layout file
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/play"
android:text="@string/play_label"></Button>
</LinearLayout>



strings.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, AudioDemo</string>
<string name="app_name">Audio Demo</string>
<string name="play_label">Play</string>
<string name="stop_label">Stop</string>
</resources>


Output

Source
http://thenewcircle.com/static/tutorials/AudioDemo.zip

Comments

Posted on Jan 13, 2010
Photo Paul Jackson
Uni
Member since Jan 13, 2010
Hi Serete,

Thanks a lot for your code. However, I tried it using a robotrock.mp3 and robotrock.wav recorded by myself, and psted within the raw folder, but it did not work in none of the cases.

Your code seems fine. I tried 2 different audio formats but none of them worked. I can't play sound. Could you please help? Thanks
Posted on Jan 13, 2010
Photo Serete Itebete
Member since Dec 23, 2009
Location: Oakland
Paul,

Thanks for the information on your own recorded mp3 format. In my case I used the .mp3 and .m4a music files-as-is and it worked fine and dropped them as you in the res/raw folder.

There are quite a number of formats that are supported by Android Platform and here is a link to page http://developer.android.com/guide/appendix/media-formats.html and since I dont know too much about audio formats and their details, I can only direct you to the link above, unless someone else has more to say.

Thanks
Posted on Jan 13, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Also, make sure you do not specify the extension when referencing the resource in your Java code. So, for example, if your music file is /res/raw/braincandy.mp3, you reference it as R.raw.braincandy without any extension. Android auto-magically figures out what extension to use.

Hope this helps!
Marko
Posted on Jan 14, 2010
Photo Paul Jackson
Uni
Member since Jan 13, 2010
Thanks a lot Serete and Marko,

The volume of my phone was too low to hear the sound, but now I can hear, which means your code is right. However, I still have a problem, since it only plays for a very brief time (less than a second) and then it stops. I'm not sure if it could be my phone not supporting the audio. I'm going to keep trying. Thanks a lot.
Posted on Jan 27, 2010
Photo Cooper Archard
UMF
Member since Jan 27, 2010
The error you are having where the music will only play for a second or two is in the OnCreate where it says "player.release()" comment this out and it will work fine.... At least it did in my case running 1.6
Posted on Mar 5, 2010
Photo A Member
Org
Member since Mar 1, 2010
I see an inconsistent behavior in the GUI between the phone and the emulator. I don't see the buttons on the phone. I see them only on the Emulator. Do you have any idea why this happens?
Posted on Mar 6, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
No clue. There should be just one button. The layout is simple enough that it shouldn't behave differently on various devices (physical or virtual).
Posted on May 6, 2010
Photo Rohan R
NA
Member since May 6, 2010
Thx a lot...very useful information.. After so many try on different example on different site, this was the best example.. thx Marko and Serete.. please keep us update on new things.

Thx

rohn
Posted on Jul 21, 2010
Photo Carl J
Hdsl
Member since Jul 21, 2010
Confirmative the code from this tutorial is working. Many thanks! However, so fare I could not succeed using RAW for music files when using Netbeans. Resources like text files works fine. Anyway, when I loaded the music file directly from the sd card of the device, then everything worked fine.
Posted on Sep 12, 2010
Photo Itsik Avidan
--
Member since Sep 12, 2010
Hey I'm trying to run your code and always when I'm calling to MediaPlayer.create() I get null as the return. I get this return on emulator and when i running in debug with G1 device .

but when I'm running the code from a different PC it works fine ...


the PC who can't run the code in Win7 32 bit , I'm working with Eclipse IDE with Android SDK
the other PC runs WinXP 32 ( it is much older so it's not a preformence issue )


Do you have a clue what could be the problem ?
thanks
Posted on Sep 29, 2010
Photo DJ HaKa
GO DJ
GO DJs
Member since Sep 29, 2010
Nice!
Now my question is, what if one wanted to stream .pls and/or .m3u? the .m3u in question contains:

Code:

http://furumoon.net:8000/kzjm


and the pls

Code:

[playlist]
NumberOfEntries=1
File1=http://furumoon.net:8002/


the m3u is an icecast streaming audio file, and the .pls is a shoutcast (winamp) streaming server. They both play audio 24/7.


Also, could this be done just using the MediaPlayer variable? I use it to play files raw (mediaplayer.create )
Posted on Jan 26, 2011
Photo Prashanth Pp
RVCE
Member since Jan 26, 2011
Thanks you very much...
what are the changes required to scan audio files from SD card and ask the user to select from it.. I just need to know the APIs to access SD card data..like the list of all files present..
Posted on Apr 6, 2011
Photo Sanoop Yadav
Student
Member since Apr 5, 2011
Thanks Serete for sharing this, Great Post!

I have a question - How we can play more than one file in Android?

Any suggestion!
Posted on Apr 7, 2011
Photo Praveen Thota
Student
Member since Apr 7, 2011
hi i had written the above same code with out changing any line by im getting some errors can any one please guide me my mail-id:praveen_4027@yahoo.com
Posted on Apr 7, 2011
Photo Sanoop Yadav
Student
Member since Apr 5, 2011
Praveen - check LogCat to see what error you are getting.

Way to open LogCat in Eclipse -
1. DDMS Perspective
2. Windows->Show View -> Others ->LogCat

Hope it make sense
Posted on Apr 9, 2011
Photo Cosma Mihai
Student
Member since Apr 6, 2011
hey, I have a question:Can u record a sound from the MIC and store it into res/raw/record_1.mp3,
for example?
Posted on Apr 17, 2011
Photo Cosma Mihai
Student
Member since Apr 6, 2011
and another thing....


I want to record a sound(= a word) from the MIC and store it to a database or SD card and add it a name . Also I want to compare it to a new sound (same word) that I say to the MIC and see if they match?

I know it's much but at least can u tell me what to use, what to start with.


Most grateful!

Misu.
Posted on Apr 18, 2011
Photo Mahesh Pusala
software developer
checksum infosoft
Member since Apr 18, 2011
problem wth R.raw

please explain how to place the audio files into our project
Posted on Apr 18, 2011
Photo Cosma Mihai
Student
Member since Apr 6, 2011
You create a new file named raw in your res folder and you put there the audio file.Make the name of the sound as simple as possible.
Posted on May 7, 2011
Photo Cosma Mihai
Student
Member since Apr 6, 2011
Hey i need some help please.I want to display a sound waveform ,and to analyze it.

The sound is a .wav type.I want to calculate the spectrum and other function.

Can anyone help?

Thanks in advance!
Posted on May 13, 2011
Photo Cosma Mihai
Student
Member since Apr 6, 2011
Hi,

I am using an EditText. Is it possible to have a part of text uneditable and the rest editable in the same EditText?

Thanks in advance
Posted on Jul 4, 2011
Photo Jeyakumaran Mayooresan
Software Engineer
Eyepax IT Consulting
Member since Jun 24, 2011
What I observed while doing this project is, Emulator can be very buggy when it comes to very big mp3 files with low bit rate but even low end device (GT540) handles it beautifully.

Now i'm gonna add a new feature to my app with media player. Thanks guys.
Posted on Sep 22, 2011
Photo Ruchita Bora
San Jose State University
Member since Sep 22, 2011
Hi, I am trying to run the above code. But I am not able hear any sound. I just downloaded above code and dropped one mp3 file in raw folder. Also when I click on close it says application closed unexpectedly. Please help me.
Posted on Sep 28, 2011
Photo Lily Lu
BCIT
Member since Aug 18, 2011
Hello. For some reason my program doesn't even load. I am getting a ClassNotFoundException and my program just crashes.