Wednesday, September 11, 2013

Android MediaPlayer Example

MediaPlayer class is  used to control playback of audio/video files and streams.
Using MediaPlayer class we can control the behavioyr of player like volume control, whether to repeat the current tarck or not, stop or pause the playback etc.

Steps:

  1. Initialize the Media Player with media to play.
  2. Prepare the Media Player for playback.
  3. Start the playback. 
  4. Pause or stop the playback prior to its completing.
  5. Playback complete.
To play a media resource you need to create a new MediaPlayer object, initialize it with a media
source, and prepare it for playback.

When you have finished playing , call the release method on your Media Player object to free the resources associated with the MediaPlayer

mediaPlayer.release();

Preparing Audio for Playback


To play back audio content using the Media Player, we need to create a new Media Player object and
set the data source of the audio (pass as paarmeter).

  • A resource identifier
  • A URI to a local file using the file
  • A URI to an online audio resource as a URL 
  • A URI to a local Content Provider row
MediaPlayer filePlayer = MediaPlayer.create(appContext,
Uri.parse("file:///sdcard/localfile.mp3"));


MediaPlayer urlPlayer = MediaPlayer.create(appContext,
Uri.parse("http://site.com/audio/audio.mp3"));


MediaPlayer contentPlayer = MediaPlayer.create(appContext,
Settings.System.DEFAULT_RINGTONE_URI)



we can also use setDataSource method to specify the resource
like

myMediaPlayerObject.setDataSource("/sdcard/music/tarck1.mp3");


Controlling The PlayBack

Skip for a particular time

mediaPlayerObject.start();
int pos = mediaPlayerObject.getCurrentPosition();
int duration = mediaPlayerObject.getDuration();
mediaPlayerObject.seekTo(pos + (duration-pos)/10);

Repeating the Audio Playback track

We can use the isLooping and setLooping methods to specify if the media being played should repeat or loop when it completes.

if (!mediaPlayer.isLooping())
mediaPlayer.setLooping(true);

Controlling the Volume of Media Player


We acn also  control the volume for each channel during playback using the setVolume method. It takes
a scalar float value between 0 and 1 for both the left and right channels (where 0 is silent and 1 is
maximum volume).

mediaPlayer.setVolume(1f, 0.5f);


MediaPlayer Example:


public class MediaPalyerActivity  extends Activity
{
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
                super.onCreate(savedInstanceState);
               
                MediaPlayer  myMediaPlayer=new MediaPlayer();
               
                try
                {
                    myMediaPlayer.setDataSource("/sdcard/music/tarck1.mp3");
                    myMediaPlayer.prepare();
                    myMediaPlayer.start();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
        }
}

 

New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swipe Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play
Android TextWatcher                               Android ExpandableListView

 Beginning With Android
      Android : Introduction(What is Android)                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Advance Views
Android Spinner                                                                           Android GalleryView
Android TabWidget                                                                      Android ExpandableListView

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage

Working With Incoming Calls                                       DataBase :  Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog
How to Hide Title Bar In Android
How to show an Activity in Landscape or Portrait Mode only.
How to Set an Image as Wallpaper.






8 comments:

  1. Hi, how to create android array sound mediaplayer with next and previous button ?

    ReplyDelete
  2. Thank you for this tutorial but i have problem can you help me at this link i post

    http://stackoverflow.com/questions/21438091/mediaplayer-logcat-errors

    ReplyDelete
  3. really very nice tips Thanks for sharing these tips. I am very impressed with this post thanks again.

    Youtube Help

    ReplyDelete
  4. The Programining Resourses Which You Have listed is most usefull for who are training Online Courses For Android Online Training contact us @ www.vibloo.com

    ReplyDelete
  5. It's a Very informative blog and useful article thank you for sharing with us, keep posting learn Android App development Course

    ReplyDelete