MediaPlayer.getDuration() - Get the Total Length of an Audio File

How to Get the Total Length of an Audio File

MediaPlayer.getDuration() was added in API Level 1
Gets the duration of the file. Returns the duration in milliseconds, if no duration is available (for example, if streaming live content), -1 is returned.

1. Create a MediaPlayer for an Audio Resource

2. Declare and Initialize an integer named intDuration, set to 0.

3. In the MainActivity.java file, add the following code. The Toast will display the duration. The intDuration will save it to an integer variable named intDuration.

if (myMediaPlayer != null) { //make sure media player was created

Toast.makeText(this, "myMediaPlayer.duration: " + myMediaPlayer.getDuration(), Toast.LENGTH_SHORT).show(); 
                       intDuration = getDuration();
               }

4. Compile and run!

Next Recommended Article:

Related Articles:

Resources:
http://developer.android.com/reference/android/media/MediaPlayer.html#getDuration()