title: What is the best way to get an audio file duration in Android?
body: <p>I'm using a <a href="http://developer.android.com/intl/zh-CN/reference/android/media/SoundPool.html" rel="nofollow noreferrer">SoundPool</a>  to play audio clips in my app. All is fine but I need to know when the clip playback has finished.</p>
  
  <p>At the moment I track it in my app by obtaining the duration of each clip using a <a href="http://developer.android.com/intl/zh-CN/reference/android/media/MediaPlayer.html" rel="nofollow noreferrer">MediaPlayer</a> instance. That works fine but it looks wasteful to load each file twice, just to get the duration. I could roughly calculate the duration myself knowing the length of the file (available from the <a href="http://developer.android.com/intl/zh-CN/reference/android/content/res/AssetFileDescriptor.html" rel="nofollow noreferrer">AssetFileDescriptor</a>) but I'd still need to know the sample rate and the number of channels.</p>
  
  <p>I see two potential solutions to that problem:</p>
  
  <ol>
  <li>Figuring out when a clip has finished playing (doesn't seem to be possible with SoundClip).</li>
  <li>Having a class which could load just the header of an audio file and give me the sample rate/number of channels (and, ideally, the sample count to get the exact duration).</li>
  </ol>
  
  <p>Any suggestions?</p>
  
  <p>Thanks,
  Max</p>
  
  <p>The code I'm using at the moment (works fine but is rather heavy for the purpose):</p>
  
  <pre><code>String[] fileNames = ...
  MediaPlayer mp = new MediaPlayer();
  for (String fileName : fileNames) {
      AssetFileDescriptor d = context.getAssets().openFd(fileName);
      mp.reset();
      mp.setDataSource(d.getFileDescriptor(), d.getStartOffset(), d.getLength());
      mp.prepare();
      int duration = mp.getDuration();
      // ...
  }
  </code></pre>
  
  <p>On a side note, this question has already been <a href="https://stackoverflow.com/questions/3357484/is-there-a-way-to-determine-the-duration-of-an-audio-file">asked</a> but got no answers.</p>