get Audio Duration - Android Media

Android examples for Media:Auto Player

Description

get Audio Duration

Demo Code


import java.io.IOException;

import android.media.MediaPlayer;
import android.util.Log;

public class Main {
  private static final String TAG = "AudioUtil";
  private static MediaPlayer mDurationPlayer = new MediaPlayer();

  public static long getAudioDuration(String fileName) throws IOException {
    long duration = 0;
    if (mDurationPlayer == null) {
      return duration;
    }/*from   ww  w. j a  v  a  2 s .  com*/
    try {
      mDurationPlayer.reset();
      mDurationPlayer.setDataSource(fileName);
      mDurationPlayer.prepare();
      duration = mDurationPlayer.getDuration();
      mDurationPlayer.stop();
    } catch (IOException e) {
      Log.e(TAG, "IOException:" + e.getMessage());
      throw e;
    } catch (IllegalStateException e) {
      Log.e(TAG, "getAudioDuration start playing IllegalStateException");
      throw e;
    }
    return duration;
  }
}

Related Tutorials